diff --git a/src/Pluf/Model/Set.php b/src/Pluf/Model/Set.php new file mode 100644 index 0000000..5ccb27c --- /dev/null +++ b/src/Pluf/Model/Set.php @@ -0,0 +1,141 @@ + 'MyApp_Item', + * 'model_id' => 32, + * 'foo' => 'bingo plus'), + * (object) array('model_class' => 'MyApp_Bong', + * 'model_id' => 12, + * 'foo' => 'youpla'), + * (object) array('model_class' => 'MyApp_Item', + * 'model_id' => 14, + * 'foo' => 'bingo'), + * ); + * + * You can do: + * $set = new Pluf_Model_Set($data, array('foo' => '_Foo')); + * foreach ($set as $res) { + * echo $res; // Will be the loaded model based on the class and id. + * echo $res->_Foo; // will contain the value foo of the $data array. + * } + * + */ +class Pluf_Model_Set implements Iterator, ArrayAccess +{ + protected $data = array(); + protected $keys = array(); + + public function __construct($data, $keys=array()) + { + $this->data = $data; + $this->keys = $keys; + reset($this->data); + } + + /** + * Get the current item. + */ + public function current() + { + $i = current($this->data); + $item = Pluf::factory($i->model_class, $i->model_id); + foreach ($this->keys as $key => $val) { + $item->$val = $i->$key; + } + return $item; + } + + public function key() + { + return key($this->data); + } + + public function next() + { + next($this->data); + } + + public function rewind() + { + reset($this->data); + } + + public function valid() + { + // We know that the boolean false will not be stored as a + // field, so we can test against false to check if valid or + // not. + return (false !== current($this->data)); + } + + public function count() + { + return count($this->data); + } + + public function offsetUnset($index) + { + unset($this->data[$index]); + } + + public function offsetSet($index, $value) + { + if (!is_object($value) or + is_subclass_of($value, 'Pluf_Model')) { + throw new Exception('Must be a subclass of Pluf_Model: '.$value); + } + $res = array('model_class' => $value->_model, + 'model_id' => $value->id); + foreach ($this->keys as $key => $name) { + $res[$key] = (isset($value->$name)) ? $value->$name : null; + } + $this->data[$index] = (object) $res; + } + + public function offsetGet($index) + { + if (!isset($this->data[$index])) { + throw new Exception('Undefined index: '.$index); + } + $i = $this->data[$index]; + $item = Pluf::factory($i->model_class, $i->model_id); + foreach ($this->keys as $key => $val) { + $item->$val = $i->$key; + } + return $item; + } + + public function offsetExists($index) + { + return (isset($this->data[$index])); + } +} \ No newline at end of file