prolic / HumusAmqpModule

AMQP module for Zend Framework 2 to integrate RabbitMQ
https://humusamqp.readthedocs.io
MIT License
31 stars 13 forks source link

Add events on Consumer and RpcServer #22

Closed thomasvargiu closed 9 years ago

thomasvargiu commented 9 years ago

In order to use any class and to maintain a clean code, will be useful to have a CallbackInterface to be implemented in any class.

It's better to implement events. The idea is to implement events on Consumer and RpcServer and use classes that implements ListenerAggregateInterface to handle events.

thomasvargiu commented 9 years ago

The configuration can be like this:

<?php

return [
    'humus_amqp_module' => [
        'consumers' => [
            'my-consumer' => [
                'queues' => array(
                    'my-queue',
                ),
                'auto_setup_fabric' => true,
                'listeners' => [
                    'Application\\My\\Listener'
                ],
            ],
        ],
    ]
];

An example of a listener can be:

<?php

namespace MyModule\Listener;

use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\EventManager\ListenerAggregateTrait;

class ConsumerListener implements ListenerAggregateInterface
{
    use ListenerAggregateTrait;

    /**
     * @param EventManagerInterface $events
     * @return void
     */
    public function attach(EventManagerInterface $events)
    {
        $this->listeners[] = $events->attach('delivery', [$this, 'onDelivery']);
        $this->listeners[] = $events->attach('flush', [$this, 'onFlush']);
        $this->listeners[] = $events->attach('error', [$this, 'onError']);
    }

    /**
     * @param EventInterface $e
     */
    public function onDelivery(EventInterface $e)
    {
        // my code here
    }

    /**
     * @param EventInterface $e
     */
    public function onFlush(EventInterface $e)
    {
        // my code here
    }

    /**
     * @param EventInterface $e
     */
    public function onError(EventInterface $e)
    {
        // my code here
    }
}

Advantages: