My Blog
My Blog

splQueue

Queue is data structure it allow to add element First in First out. adding data at the back and reading data from front . in PHP queue can bee seen as standard DoublyLinkedList it  extend SplDoublyLinkedList  Inherit all methods from SplDoublyLinkedList. SplQueue have an two extra two methods which are enqueue() and dequeue() these methods alias for push() and  shift()

SplQueue come with default iterative mode of IT_MODE_FIFO | IT_MODE_KEEP. you able to change to IT_MODE_DELETE but can’t change to IT_MODE_LIFO

USAGE

use SplQueue when you need to store data and fetch data in the same order. Below example creates an event handler where you can hook your own functions

$eventHandler = new SplQueue();

$eventHandler->enqueue("function1");
$eventHandler->enqueue("function2");

while (!$eventHandler->isEmpty()) {
    $event = (string)$eventHandler->dequeue();

    if (function_exists($event)) {

        $event($eventHandler);
    }
}

function function1(SplQueue $eventHandler)
{
    print "Function 1 called. " .
        "Adding function3() to the event handler\n";
    $eventHandler->enqueue("function3");
    $eventHandler->enqueue("a message for function 3");
}

function function2(SplQueue $eventHandler)
{
    print "Function 2 called.\n";
}

function function3(SplQueue $eventHandler)
{
    $msg = $eventHandler->dequeue();
    print "Function 3 called. Message: $msg\n";
}