Skip to content

Instantly share code, notes, and snippets.

@kevinmlong
Last active June 1, 2017 14:54
Show Gist options
  • Save kevinmlong/00dde2cd93be24e615b85229e8cb3e8b to your computer and use it in GitHub Desktop.
Save kevinmlong/00dde2cd93be24e615b85229e8cb3e8b to your computer and use it in GitHub Desktop.
Postmaster Class for PHP Event Bus Using RabbitMQ
<?php
class Postmaster {
private $connection;
private $channel;
/**
* Factory method for creating and instance of Postmaster
*/
public static function create() {
return new Postmaster();
}
public function __construct() {
/* get a connection and channel reference */
$this->connection = new AMQPStreamConnection('127.0.0.1', 5672, 'guest', 'guest');
$this->channel = $this->connection->channel();
/* Make sure the queues we need are set up */
$this->channel->queue_declare(LETTER_PARCEL_QUEUE_ID,false, false, false , false);
}
/**
* This ensures the channel and connection reference are cleaned up appropriately.
*/
public function __destruct()
{
$this->channel->close();
$this->connection->close();
}
/**
* This is called by the producers when they want to send a parcel to a Carrier
*/
public function send(Parcel $parcel) {
if (null === $parcel) {
throw new \InvalidArgumentException('You can not provide a null parcel!');
}
return $this->pushToQueue($parcel);
}
private function pushToQueue(Parcel $parcel) {
$queueName = null;
$queueMessage = new AMQPMessage(serialize($parcel));
/* Only push certain types of parcels to certain queues */
switch (true) {
/* Provided cases for matching queueName */
case $parcel instanceof Letter:
$queueName = LETTER_PARCEL_QUEUE_ID
}
/* Check if the queueName is set - if not - drop on the floor */
if ($queueName) {
try {
$this->channel->basic_publish($queueMessage, '', $queueName);
} catch (Exception $e) {
return false;
}
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment