Created
May 17, 2010 02:26
-
-
Save dhotson/403335 to your computer and use it in GitHub Desktop.
This file contains 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 | |
class DomainObject | |
{ | |
public function __construct($arr = array()) | |
{ | |
foreach($arr as $key => $value) | |
$this->$key = $value; | |
$this->_attributes = new Attributes(); | |
$this->_relationships = new Relationships(); | |
if (is_callable(array($this, 'configure'))) | |
$this->configure($attributes, $relationships); | |
} | |
public static function new($arr = array()) | |
{ | |
return new static($arr); | |
} | |
} | |
class User extends DomainObject | |
{ | |
public function configure($attributes, $relationships) | |
{ | |
$attributes | |
->field('userid', Serial(), array('primary'=>true)) | |
->field('firstname', String(255)) | |
->field('lastname', String(255)) | |
; | |
// .. or with some __call() magic .. | |
$attributes | |
->userid(Serial(), array('primary'=>true)) | |
->firstname(String(255)) | |
->lastname(String(255)) | |
; | |
$relationships | |
->hasOne('Group', 'groupid') | |
->hasMany(...) | |
->belongsTo(...) | |
; | |
} | |
} | |
// alternatives for creating objects: | |
$user = new User(); | |
$user->firstname = 'Franklin'; | |
$user->lastname = 'Brown'; | |
$user->age = 27; | |
$user = User::new(array( | |
'firstname' => 'Franklin', | |
'lastname' => 'Brown', | |
'age' => 27, | |
)); | |
$user = new User(array( | |
'firstname' => 'Franklin', | |
'lastname' => 'Brown', | |
'age' => 27, | |
)); | |
// alternatives for saving objects: | |
$user->save(); | |
User::save($user); | |
User::mapper()->save($user); | |
Pheasant::mapper($user)->save(); | |
// simple relationship lookups: | |
$group = $user->group; // equivalent to Group::findOneBySql('groupid = ?', $user->groupid) | |
// .. might be too deceptive because it hides the fact it's actually a db query | |
$group = $user->getGroup(); | |
$groups = $user->getGroups(); // Plural name magic, one to many lookup | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One small note, User::new won't work, PHP will bitch because it's a special word and its parser can't handle it. I've settled on using a static construct method e.g. User::construct instead.