Tailable Cursor
Tailable Cursor
_php-tailable-cursor:
=========================
Tailable Cursor Iteration
=========================
.. default-domain:: mongodb
Overview
--------
While normal cursors can be iterated once with ``foreach``, that approach will
not work with tailable cursors. When ``foreach`` is used with a tailable cursor,
the loop will stop upon reaching the end of the initial result set. Attempting
to continue iteration on the cursor with a second ``foreach`` would throw an
exception, since PHP attempts to rewind the cursor.
In order to continuously read from a tailable cursor, we will need to wrap the
Cursor object with an :php:`IteratorIterator <iteratoriterator>`. This will
allow us to directly control the cursor's iteration (e.g. call ``next()``),
avoid inadvertently rewinding the cursor, and decide when to wait for new
results or stop iteration entirely.
The following example finds five restaurants and uses ``foreach`` to view the
results:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->test->restaurants;
While this example is quite concise, there is actually quite a bit going on. The
``foreach`` construct begins by rewinding the iterable (``$cursor`` in this
case). It then checks if the current position is valid. If the position is not
valid, the loop ends. Otherwise, the current key and value are accessed
accordingly and the loop body is executed. Assuming a :php:`break <break>` has
not occurred, the iterator then advances to the next position, control jumps
back to the validity check, and the loop continues.
With the inner workings of ``foreach`` under our belt, we can now translate the
preceding example to use IteratorIterator:
.. code-block:: php
<?php
$iterator->rewind();
while ($iterator->valid()) {
$document = $iterator->current();
var_dump($document);
$iterator->next();
}
.. note::
.. code-block:: php
<?php
$database = (new MongoDB\Client)->test;
$database->createCollection('capped', [
'capped' => true,
'size' => 16777216,
]);
$collection = $database->selectCollection('capped');
while (true) {
$collection->insertOne(['createdAt' => new MongoDB\BSON\UTCDateTime()]);
sleep(1);
}
With the producer script still running, we will now execute a consumer script to
read the inserted documents using a tailable cursor, indicated by the
``cursorType`` option to :phpmethod:`MongoDB\\Collection::find()`. We'll start
by using ``foreach`` to illustrate its shortcomings:
.. code-block:: php
<?php
$cursor = $collection->find([], [
'cursorType' => MongoDB\Operation\Find::TAILABLE_AWAIT,
'maxAwaitTimeMS' => 100,
]);
If you execute this consumer script, you'll notice that it quickly exhausts all
results in the capped collection and then terminates. We cannot add a second
``foreach``, as that would throw an exception when attempting to rewind the
cursor. This is a ripe use case for directly controlling the iteration process
using :php:`IteratorIterator <iteratoriterator>`.
.. code-block:: php
<?php
$cursor = $collection->find([], [
'cursorType' => MongoDB\Operation\Find::TAILABLE_AWAIT,
'maxAwaitTimeMS' => 100,
]);
$iterator->rewind();
while (true) {
if ($iterator->valid()) {
$document = $iterator->current();
printf("Consumed document created at: %s\n", $document->createdAt);
}
$iterator->next();
}
Much like the ``foreach`` example, this version on the consumer script will
start by quickly printing all results in the capped collection; however, it will
not terminate upon reaching the end of the initial result set. Since we're
working with a tailable cursor, calling ``next()`` will block and wait for
additional results rather than throw an exception. We will also use ``valid()``
to check if there is actually data available to read at each step.
Since we've elected to use a ``TAILABLE_AWAIT`` cursor, the server will delay
its response to the driver for a set amount of time. In this example, we've
requested that the server block for approximately 100 milliseconds by specifying
the ``maxAwaitTimeMS`` option to :phpmethod:`MongoDB\\Collection::find()`.