Skip to content

Instantly share code, notes, and snippets.

@jeremyharris
Created June 8, 2017 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyharris/a4904c7dca884209a4a3063887536eb7 to your computer and use it in GitHub Desktop.
Save jeremyharris/a4904c7dca884209a4a3063887536eb7 to your computer and use it in GitHub Desktop.
queue manager
<?php
namespace App\Queue;
use Cake\Event\Event;
use Cake\Event\EventManager;
use josegonzalez\Queuesadilla\Job;
use Josegonzalez\CakeQueuesadilla\Queue\Queue;
/**
* QueueManager
*
* Like EventManager, but for Queues. Use QueueManager to queue regular Events
* into a proper job queue that are fired when the worker runs
*/
class QueueManager
{
/**
* Queued events. For testing mostly
*
* @var array
*/
protected static $queued = [];
/**
* Sets the queued list
*
* @param array $queued
* @return void
*/
public static function setQueuedList($queued)
{
static::$queued = $queued;
}
/**
* Places an event in the job queue
*
* @param Event $event
* @return void
*/
public static function queue(Event $event)
{
static::$queued[] = $event;
Queue::push('\App\Queue\QueueManager::dispatchEvent', [get_class($event), $event->getName(), $event->getData()]);
}
/**
* Gets events that were queued during this request
*
* @return array
*/
public static function getQueuedList()
{
return static::$queued;
}
/**
* Constructs and dispatches the event from a job
*
* ### Data array
* - 0: event FQCN
* - 1: event name
* - 2: event data array
*
* @param Job\Base $job Job
* @return void
*/
public static function dispatchEvent($job)
{
$eventClass = $job->data(0);
$eventName = $job->data(1);
$data = $job->data(2, []);
$event = new $eventClass($eventName, null, $data);
EventManager::instance()->dispatch($event);
}
}
@jeremyharris
Copy link
Author

Usage:

QueueManager::queue(new Event('My.Event', null, ['data' => 'passed']);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment