我正在寻找一个有效的解决方案,在symfony2中迭代一个mongodb .不幸的是,这似乎不起作用?Symfony忽略了这个功能!PersistentCollection
next()
while (($animal = $zooAnimals->next()) !== false) { $color = $animal->getColor(); print_r($color); die; // Test and die } print_r('Where are the animals?'); die; // << Current result
参考:Doctrine\ODM\MongoDB\PersistentCollection
这不是Symfony的"错误".这是对如何迭代对象的误解.有几种方法可以为您的用例处理此问题.这里有一些
你的PersistentCollection
工具Collection
实现了IteratorAggregate
哪些实现(长路嘿?).
实现接口的对象可以在语句中使用.Traversable
Traversable
foreach
IteratorAggregate
强迫你实现一个getIterator
必须返回的方法Iterator
.最后还实现了Traversable
接口.
Iterator
interface强制你的对象声明5个方法,以供a使用 foreach
class MyCollection implements Iterator { protected $parameters = array(); protected $pointer = 0; public function add($parameter) { $this->parameters[] = $parameter; } /** * These methods are needed by Iterator */ public function current() { return $this->parameters[$this->pointer]; } public function key() { return $this->pointer; } public function next() { $this->pointer++; } public function rewind() { $this->pointer = 0; } public function valid() { return array_key_exists($this->pointer, $this->parameters); } }
您可以使用任何实现Iterator
它的类 -Demo file
$coll = new MyCollection; $coll->add('foo'); $coll->add('bar'); foreach ($coll as $key => $parameter) { echo $key, ' => ', $parameter, PHP_EOL; }
为了像 foreach 一样使用这个类.方法应该这样调用 - Demo file
$coll->rewind(); while ($coll->valid()) { echo $coll->key(), ' => ', $coll->current(), PHP_EOL; $coll->next(); }