Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom attributes serialization and access #243

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,13 @@ public function &__get($name)
$value = $this->$name();
return $value;
}

// or a method with the same name as the property
else if (method_exists($this, $name))
{
$value = $this->$name();
return $value;
}
// delegete read_attribute()
return $this->read_attribute($name);
}

Expand Down
7 changes: 7 additions & 0 deletions lib/Serialization.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,14 @@ private function check_methods()
foreach ($this->options['methods'] as $method)
{
if (method_exists($this->model, $method))
{
$this->attributes[$method] = $this->model->$method();
}
else if (method_exists($this->model, "get_{$method}"))
{
$getter = "get_{$method}";
$this->attributes[$method] = $this->model->$getter();
}
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions test/SerializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,16 @@ public function test_methods_method_same_as_attribute()
$this->assert_equals('ancient art of main tanking', $a['name']);
}

public function test_methods_uses_getter_if_method_does_not_exist() {
$a = $this->_a(array('methods' => 'lower_name'));
$this->assert_equals('ancient art of main tanking', $a['lower_name']);
}

public function test_methods_method_has_precedence_over_getter() {
$a = $this->_a(array('methods' => 'name'));
$this->assert_equals('ancient art of main tanking', $a['name']);
}

public function test_include()
{
$a = $this->_a(array('include' => array('author')));
Expand Down