开发者

PHP: Can iterator_to_array() throw an exception on a MongoCursor

Can using iterator_to_array() on a MongoCursor instance throw an exception in PHP 5.3? In other words, do I need to wrap iterator_to_array() 开发者_运维知识库calls on MongoCursor instances in try-catch statements or not?

e.g.,

$mongo = new Mongo();
$mongo_db = $mongo['my_database'];
$mongo_coll = $mongo_db['my_collection'];

// This

$cursor = $mongo_coll->find();
$documents = iterator_to_array($cursor);

// Versus this.

$cursor = $mongo_coll->find();
try {
    $documents = iterator_to_array($cursor);
} catch (Exception $e) {
    //...
}


iterator_to_array() can throw exceptions because it calls next().


I think the first comment as of now on this page http://www.php.net/manual/en/mongo.queries.php will be of interest to you, but don't know if it will be first when you view it so here is the deal.

You can check if the cursor is valid by using $cursor->valid(). And the comment says that you might have to rewind the cursor after receiving it, as it is sometime not rewound when received.

...
$cursor = $mongo_coll->find();
$cursor->rewind();
if ($cursor->valid()) {
    $documents = iterator_to_array($cursor);
}

The advantage to the above try catch block is that the try catch block might throw the exception while you could have used the cursor when the cursor was actually valid.


Find method returns Traversable object or throws an exception.

Iterator_to_array is accepting Traversable object.

Exception should appear only if something really bad happens in Mongo driver or in Mongo during iteration. Maybe disconnection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜