Symfony2 Doctrine迭代,而next()

mat*_*e64 2 php loops mongodb symfony doctrine-orm

我正在寻找一个有效的解决方案,在迭代一个 .不幸的是,这似乎不起作用?Symfony忽略了这个功能!PersistentCollectionnext()

while (($animal = $zooAnimals->next()) !== false) {

    $color = $animal->getColor();

    print_r($color); die; // Test and die
}

print_r('Where are the animals?'); die; // << Current result
Run Code Online (Sandbox Code Playgroud)

参考:Doctrine\ODM\MongoDB\PersistentCollection

Tou*_*uki 8

这不是Symfony的"错误".这是对如何迭代对象的误解.有几种方法可以为您的用例处理此问题.这里有一些

使用foreach!

你的PersistentCollection工具Collection实现了IteratorAggregate哪些实现(长路嘿?). 实现接口的对象可以在语句中使用.Traversable
Traversableforeach

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用任何实现Iterator它的类 -Demo file

$coll = new MyCollection;
$coll->add('foo');
$coll->add('bar');

foreach ($coll as $key => $parameter) {
    echo $key, ' => ', $parameter, PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)

暂时使用迭代器

为了 foreach 一样使用这个类.方法应该这样调用 - Demo file

$coll->rewind();

while ($coll->valid()) {
    echo $coll->key(), ' => ', $coll->current(), PHP_EOL;
    $coll->next();
}
Run Code Online (Sandbox Code Playgroud)