Skip to content

Instantly share code, notes, and snippets.

@dhotson
Created May 17, 2010 02:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhotson/403335 to your computer and use it in GitHub Desktop.
Save dhotson/403335 to your computer and use it in GitHub Desktop.
<?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
@rbone
Copy link

rbone commented May 17, 2010

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment