Skip to content

Instantly share code, notes, and snippets.

@amcsi
Last active August 29, 2015 13:59
Show Gist options
  • Save amcsi/10989673 to your computer and use it in GitHub Desktop.
Save amcsi/10989673 to your computer and use it in GitHub Desktop.
Immutable value object
<?php
namespace MyProject;
class Person
{
private $data;
/**
*
* [
* 'id' => <id>,
* 'name' => 'name',
* 'insertDate' => '2014-04-17 15:53:00'
* ]
*
* @param array $data
**/
public function __construct(array $data)
{
$this->data = $data;
}
/**
* @return string
**/
public function getInsertTime()
{
return strtotime($this->data['insertDate']);
}
/**
* __get
*
* @param mixed string
* @access public
* @return mixed
*/
public function __get($name)
{
static $forbidden = array('insertDate');
if (array_key_exists($name, $this->data) && !in_array($name, $forbidden)) {
switch ($name) {
case 'insertTime':
$ret = $this->getInsertTime();
break;
default:
$ret = $this->data[$name];
break;
}
} else {
throw new \DomainException("No such key: `$name`");
}
return $ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment