Created
March 1, 2012 01:38
-
-
Save clexmond/1946493 to your computer and use it in GitHub Desktop.
Implementing custom getters and setters in Lithium
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 | |
namespace path\to\lib; | |
use \lithium\data\entity\Record; | |
/** | |
* This class can extend either \lithium\data\entity\Record or \lithium\data\entity\Document | |
* and takes care of automatically calling getters and setters in the format getProperty and | |
* setProperty. | |
* | |
* Implement by adding the following to the connection in your connections.php bootstrap: | |
* 'classes' => array('entity' => 'path\to\lib\Entity') | |
* | |
* @see lithium\data\Entity | |
*/ | |
class Entity extends Record { | |
/** | |
* Extends custom getter to allow for custom getters | |
* | |
* @see \lithium\data\Entity::__get | |
*/ | |
public function &__get($name) { | |
if (isset($this->_relationships[$name])) { | |
return $this->_relationships[$name]; | |
} | |
if (isset($this->_updated[$name])) { | |
$model = $this->_model; | |
$method = 'get' . ucfirst($name); | |
if (method_exists($model, $method)) { | |
$result = $this->$method(); | |
return $result; | |
} | |
return $this->_updated[$name]; | |
} | |
$null = null; | |
return $null; | |
} | |
/** | |
* Extends magic setter to allow for custom setters | |
* | |
* @see \lithium\data\Entity::__set | |
*/ | |
public function __set($name, $value = null) { | |
if (is_array($name) && !$value) { | |
return array_map(array(&$this, '__set'), array_keys($name), array_values($name)); | |
} | |
$model = $this->_model; | |
$method = 'set' . ucfirst($name); | |
if (method_exists($model, 'set' . ucfirst($name))) { | |
$value = $this->$method($value); | |
} | |
$this->_updated[$name] = $value; | |
} | |
} |
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 | |
namespace path\to\lib; | |
class Model extends \lithium\data\Model { | |
/** | |
* Over-ridden create method to prevent passing data. This enforces all data applied | |
* to a model being fed through the magic setter. | |
* | |
* @see \lithium\data\Model::create | |
*/ | |
public static function create(array $data = array(), array $options = array()) { | |
$new = parent::create(array(), $options); | |
$new->set($data); | |
return $new; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment