Created
July 9, 2011 16:58
-
-
Save jasongrimes/1073746 to your computer and use it in GitHub Desktop.
Collection class that can be used with Zend_Paginator
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
class Jg_Mapper_Collection implements Iterator, Countable, Zend_Paginator_Adapter_Interface { | |
protected $_mapper; | |
protected $_total; | |
protected $_raw = array(); | |
protected $_domain_object_class; | |
protected $_result; | |
protected $_pointer = 0; | |
protected $_objects = array(); | |
public function __construct(array $raw, Jg_Mapper $mapper, $domain_object_class) { | |
$this->_raw = $raw; | |
$this->_total = count($raw); | |
$this->_mapper = $mapper; | |
$this->_domain_object_class = $domain_object_class; | |
} | |
public function add($object) { | |
if (!($object instanceof $this->_domain_object_class)) { | |
throw new Exception('This is a "' . $this->_domain_object_class. '" collection'); | |
} | |
$this->_objects[$this->count()] = $object; | |
$this->_total++; | |
} | |
protected function _getRow($num) { | |
$this->_notifyAccess($num); | |
if ($num >= $this->_total || $num < 0) { | |
return null; | |
} | |
if (!isset($this->_objects[$num]) && isset($this->_raw[$num])) { | |
$this->_objects[$num] = $this->_mapper->createObject($this->_raw[$num]); | |
} | |
return $this->_objects[$num]; | |
} | |
public function rewind() { | |
$this->_pointer = 0; | |
} | |
public function current() { | |
return $this->_getRow($this->_pointer); | |
} | |
public function key() { | |
return $this->_pointer; | |
} | |
public function next() { | |
$row = $this->_getRow($this->_pointer); | |
if ($row) { | |
$this->_pointer++; | |
} | |
return $row; | |
} | |
public function valid() { | |
return !is_null($this->current()); | |
} | |
public function count() { | |
return $this->_total; | |
} | |
/** | |
* Returns an array of items for a page. Called by Zend_Paginator. | |
* | |
* @param integer $offset Page offset | |
* @param integer $itemCountPerPage Number of items per page | |
* @return array | |
*/ | |
public function getItems($offset, $itemCountPerPage) { | |
$this->_notifyAccess($offset, $itemCountPerPage); | |
$items = array(); | |
for ($i = $offset; $i < ($offset + $itemCountPerPage); $i++) { | |
$items[] = $this->_getRow($i); | |
} | |
return $items; | |
} | |
protected function _notifyAccess($offset, $length = 1) { | |
// Empty on purpose. Child classes can extend to support lazy loading | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment