Created
March 13, 2012 14:55
-
-
Save nlenepveu/2029268 to your computer and use it in GitHub Desktop.
Model abstraction - class App_Model_Abstract
This file contains hidden or 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 | |
abstract class App_Model_Abstract | |
{ | |
/** | |
* @var App_Model_AbstractMapper | |
*/ | |
protected $_mapper; | |
/** | |
* Public constructor | |
* | |
* @param array $row | |
* @param App_Model_AbstractMapper $mapper | |
*/ | |
public function __construct(array $row = null, App_Model_AbstractMapper $mapper = null) | |
{ | |
if ($row) { | |
$this->initialize($row); | |
} | |
$this->setMapper($mapper ?: $this->_getDefaultMapper()); | |
} | |
/** | |
* Initialize the data | |
* | |
* @param array|Traversable $row | |
* | |
* @return App_Model_Abstract | |
*/ | |
public function initialize($row) | |
{ | |
if (!is_array($row) && ! $row instanceof Traversable) { | |
throw new Exception("Row parameter should be an array or implements Traversable interface"); | |
} | |
foreach ($row as $key => $value) { | |
$this->$key = $value; | |
} | |
return $this; | |
} | |
/** | |
* Set the Mapper instance | |
* | |
* @param App_Model_AbstractMapper $mapper | |
* | |
* @return App_Model_Abstract | |
*/ | |
public function setMapper(App_Model_AbstractMapper $mapper) | |
{ | |
$this->_mapper = $mapper; | |
return $this; | |
} | |
/** | |
* Get the associated Mapper instance | |
* | |
* @return App_Model_AbstractMapper | |
*/ | |
public function getMapper() | |
{ | |
return $this->_mapper; | |
} | |
/** | |
* Return the default linked Mapper | |
* | |
* @return App_Model_AbstractMapper | |
*/ | |
protected function _getDefaultMapper() | |
{ | |
$className = get_class($this) . 'Mapper'; | |
if (! class_exists($className, true)) { | |
throw new Exception(sprintf("No default Mapper defined for the model %s, %s expected", get_class($this), $className)); | |
} | |
return new $className; | |
} | |
/** | |
* Proxy to mapper insert | |
* | |
* @return App_Model_Abstract | |
*/ | |
public function insert() | |
{ | |
$this->getMapper()->insert($this); | |
return $this; | |
} | |
/** | |
* Proxy to mapper update | |
* | |
* @return App_Model_Abstract | |
*/ | |
public function update() | |
{ | |
$this->getMapper()->update($this); | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment