Created
February 18, 2014 22:01
-
-
Save codenamegary/9081209 to your computer and use it in GitHub Desktop.
Example of how to use DataContain to make entities.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include __DIR__.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php'; | |
class Entity extends DataContain\Container { | |
/** | |
* @var DataContain\DefinitionContainer | |
*/ | |
protected $attributes; | |
public function __construct(array $data = array(), DataContain\DefinitionContainer $attributes = null) | |
{ | |
// Make a new definition container if one isn't passed | |
if(null === $attributes) $attributes = new DataContain\DefinitionContainer; | |
// Set some attributes for this entity | |
$this->attributes = $attributes; | |
// Call the actual 'DataContain\Container' constructor | |
parent::__construct($data, $attributes); | |
} | |
// Must implement | |
public function getDefinitionConfig() | |
{ | |
return $this->attributes; | |
} | |
} | |
class User extends Entity { | |
public function __construct(array $data = array()) | |
{ | |
// Whip up some attributes for this puppy | |
$firstnameAttribute = new DataContain\Definition('firstname', false, '', 'string'); | |
$roleAttribute = new DataContain\Definition('role', true, 'user', 'string'); | |
// Shove them into a definition container | |
$attributes = new DataContain\DefinitionContainer(array($firstnameAttribute, $roleAttribute)); | |
// Manually set the role, else this thing throws an exception | |
$data['role'] = 'user'; | |
// Call the Entity constructor | |
parent::__construct($data, $attributes); | |
} | |
} | |
// Note: If 'firstname' attribute definition is set to 'required', this throws an exception. | |
// It doesn't necessarily makes sense to do that. There are plenty of times when you may | |
// want to just get an instance of an object and set its properties later. | |
$user = new User; | |
// Just dumps for testing | |
var_dump($user->getArrayCopy()); | |
// Throws exception, which is expected | |
var_dump($user['email']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment