. */ /** * Doctrine_Resource_Collection * * @author Konsta Vesterinen * @author Jonathan H. Wage * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @version $Revision$ * @category Object Relational Mapping * @link www.phpdoctrine.com * @since 1.0 */ class Doctrine_Resource_Collection extends Doctrine_Resource_Access implements Countable, IteratorAggregate { protected $_data = array(); protected $_config = array(); protected $_model = null; protected $_parent = null; public function __construct($model) { $this->_model = $model; } public function setParent($parent) { $this->_parent = $parent; } public function getConfig($key = null) { return Doctrine_Resource_Client::getInstance()->getConfig($key); } public function count() { return count($this->_data); } public function get($key) { if (!$key || !isset($this->_data[$key])) { return $this->add(); } else { return $this->_data[$key]; } } public function set($key, $value) { if (!$key || !isset($this->_data[$key])) { $this->_data[$key] = $value; } else { $val = $this->add(); $val->_data[$key] = $value; } } public function add($value = null) { if (!$value) { $model = $this->_model; $value = new $model(false); $table = $value->getTable(); $relation = $table->getRelationByClassName(get_class($this->_parent)); $alias = $relation['alias']; if ($relation['type'] === Doctrine_Relation::ONE) { $value->set($alias, $this->_parent); } else { $collection = new Doctrine_Resource_Collection($relation['class']); $collection[] = $this->_parent; $value->set($alias, $collection); } } $this->_data[] = $value; return $value; } public function getIterator() { return new ArrayIterator($this->_data); } public function getFirst() { return isset($this->_data[0]) ? $this->_data[0]:null; } public function toArray($deep = false) { $array = array(); foreach ($this->_data as $key => $record) { if ($record->exists() || $record->hasChanges()) { $array[$this->_model . '_' .$key] = $record->toArray($deep); } } return $array; } public function save() { foreach ($this as $record) { $record->save(); } } public function delete() { foreach ($this as $record) { $record->delete(); } } }