Permalink
Browse files

Add, document and test setter behaviour on MagicModel.

  • Loading branch information...
1 parent c31d86c commit 29b6561ed748c13e5c1f69ead632080a6da17268 @lukemorton lukemorton committed Apr 29, 2012
Showing with 63 additions and 19 deletions.
  1. +30 −0 README.md
  2. +25 −17 classes/Gignite/TheCure/Models/Magic.php
  3. +8 −2 test/ModelMagicTest.php
View
30 README.md
@@ -199,3 +199,33 @@ $model = $container->mapper('Profile')->find_one($id);
?>
```
+## Magic
+
+Usually I try to avoid magic code but expressing fields and
+relationships is repetative and I believe some so-called magic
+is acceptable in specialised areas.
+
+``` php
+<?php
+use Gignite\TheCure\Models\Magic as MagicModel;
+class User extends MagicModel {
+
+ public static function fields()
+ {
+ return array(
+ 'name' => new Field('name'),
+ 'age' => new Field('age'),
+ 'friends' => new OneToManyRelationship('friends', array(
+ 'mapper_suffix' => 'User',
+ 'model_suffix' => 'Admin',
+ )),
+ );
+ }
+
+}
+$user = new User;
+$user->name('Luke');
+echo $user->name();
+?>
+```
+
View
42 classes/Gignite/TheCure/Models/Magic.php
@@ -62,32 +62,40 @@ public function __call($method, $args)
$fields = static::fields();
$object = $this->__object();
- if (isset($fields[$method]) AND ! $args)
+ if ($field_action = $this->relation_action($fields, $method, $args))
+ {
+ list($field, $action) = $field_action;
+ $field->{$action}($this->__container(), $object, $args[0]);
+ }
+ elseif (isset($fields[$method]))
{
$field = $fields[$method];
- if (isset($object->{$field->name()}))
+ if ($args)
{
- $value = $object->{$field->name()};
+ $object->{$field->name()} = $args[0];
+ return;
}
else
{
- $value = NULL;
- }
+ if (isset($object->{$field->name()}))
+ {
+ $value = $object->{$field->name()};
+ }
+ else
+ {
+ $value = NULL;
+ }
- if ($field instanceOf Relationship)
- {
- return $field->find($this->__container(), $value);
+ if ($field instanceOf Relationship)
+ {
+ return $field->find($this->__container(), $value);
+ }
+ else
+ {
+ return $value;
+ }
}
- else
- {
- return $value;
- }
- }
- elseif ($field_action = $this->relation_action($fields, $method, $args))
- {
- list($field, $action) = $field_action;
- $field->{$action}($this->__container(), $object, $args[0]);
}
else
{
View
10 test/ModelMagicTest.php
@@ -46,15 +46,21 @@ public function providerTestMagicCall()
$luke = $this->user($expectedName);
return array(
- array($luke, $expectedName),
+ array($luke, $expectedName, array()),
+ array($luke, $expectedName, array($expectedName)),
);
}
/**
* @dataProvider providerTestMagicCall
*/
- public function testMagicCall($model, $expectedName)
+ public function testMagicCall($model, $expectedName, $args)
{
+ if ($args)
+ {
+ call_user_func_array(array($model, 'name'), $args);
+ }
+
$this->assertSame($expectedName, $model->name());
}

0 comments on commit 29b6561

Please sign in to comment.