forked from zendframework/ZendQueue
-
Notifications
You must be signed in to change notification settings - Fork 3
Example Usage
Leonardo Grasso edited this page Mar 19, 2014
·
1 revision
The below example of ZendQueue\Queue
shows a variety of basic features, including queue creation, queue retrieval, message retrieval, message deletion, and sending messages.
use ZendQueue\Queue;
use ZendQueue\Adapter\ArrayAdapter;
// Create an array queue adapter
$adapter = new ArrayAdapter();
// Create a queue object
$queue = new Queue('queue1', $adapter);
// Ensure queue1 exists in the backend
$queue->ensureQueue();
// Create a new queue object
$queue2 = new Queue('queue2', $adapter);
// Ensure queue2 exists in the backend
$queue2->ensureQueue();
// Get list of queues
foreach ($adapter->listQueues() as $name) {
$this->assertStringStartsWith('queue', $name); //echo $name, "\n";
}
// Send a message to queue1
$queue->send('My Test Message');
// Get number of messages in a queue1 (supports Countable interface from SPL)
$this->assertCount(1, $queue);//echo count($queue);
// Get up to 5 messages from a queue1
$messages = $queue->receive(5);
foreach ($messages as $i => $message) {
$this->assertSame('My Test Message', $message->getContent()); //echo $message->getContent(), "\n";
// We have processed the message; now we remove it from the queue.
$queue->delete($message);
}
// Delete a queue we created and all of it's messages
$queue->deleteQueue();
use ZendQueue\Queue;
use ZendQueue\QueueEvent;
$queue->getEventManager()->attach(QueueEvent::EVENT_RECEIVE, function (QueueEvent $e) use ($queue) {
$message = $e->getMessages()->current();
//do some work
...
$queue->delete($message);
});
//Wait for incoming messages
$queue->await();
Static factory example:
use ZendQueue\Queue;
$config = array(
'name' => 'myqueue',
'options' => array(
'messageClass' => 'Zend\Stdlib\Message'
),
'adapter' => array(
'driver' => 'Pdo_mysql',
'dsn' => 'mysql:dbname=zfqueue;host=127.0.0.1',
'username' => 'root',
'password' => '',
'driver_options' => array(
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
);
$queue = Queue::factory($config);
Using abstract service factories, register in the ServiceManager
the provided factories:
'service_manager' => array(
'abstract_fatories' => array(
'ZendQueue\Service\QueueAdapterAbstractServiceFactory',
'ZendQueue\Service\QueueAbstractServiceFactory',
),
)
Then:
'queue_adapters' => array(
'My\FooAdapter' => array(
'adapter' => 'ArrayAdapter',
'options' => array('dummyOption' => 'dummyValue'),
),
),
'queues' => array(
'queueA' => array(
'name' => 'A',
'adapter' => array( //Adapter as config
'adapter' => 'ArrayAdapter',
'options' => array('dummyOption' => 'dummyValue'),
),
),
'queueB' => array(
'name' => 'B',
'adapter' => $adapter, //Adapter as instance
),
'queueC' => array(
'name' => 'C',
'adapter' => 'My\FooAdapter', //Adapter as service name
),
)