Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Move out your listeners from Module class

Posted in Tutorial PHP, Zend Framework 2 by samsonasik on January 8, 2014

zf2-zendframework2 As we already knew. We can have ‘listeners’ with array callback that placed on Module class which can be called via onBootstrap() method. When our application is growing, to many methods on Module class will make project maintenance take harder, and make our application less-readable.
Here is a sample if we don’t have move out the method yet :

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $app            = $e->getApplication();
        $eventManager   = $app->getEventManager();

        $eventManager->attach('dispatch.error',
                array($this, 'handleDispatchErrorWithLogger'), 100);
    }

    public function handleDispatchErrorWithLogger(MvcEvent $e)
    {
        $exception = $e->getParam('exception');

        //it is just a sample, you can create service for logger
        $writer = new \Zend\Log\Writer\Stream('./data/logs/'.date('Y-m-d').'-log.txt');
        $log      = new \Zend\Log\Logger();
        $log->addWriter($writer);

        $log->err($exception);
    }
    public function getConfig(){/*common code*/}
    public function getAutoloaderConfig(){/*common code*/}
}

And many more when application growing, so, this is how it can be moved out :
1. Create a class that has __invoke method that will be fired when event triggered

class DispatchErrorHandlerListener
{
    public function __invoke(MvcEvent $e)
    {
        $exception = $e->getParam('exception');

        //it is just a sample, you can create service for logger
        $writer = new \Zend\Log\Writer\Stream('./data/logs/'.date('Y-m-d').'-log.txt');
        $log      = new \Zend\Log\Logger();
        $log->addWriter($writer);

        $log->err($exception);
    }
}

2. Make the listener as object

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $app            = $e->getApplication();
        $eventManager   = $app->getEventManager();

        $eventManager->attach('dispatch.error', new \Tutorial\Listener\DispatchErrorHandlerListener, 100);
    }

    public function getConfig(){/*common code*/}
    public function getAutoloaderConfig(){/*common code*/}
}

and if you like the listener as service, you can pass like this :

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $app            = $e->getApplication();
        $eventManager   = $app->getEventManager();
        $service        = $app->getServiceManager();

        $eventManager->attach('dispatch.error', $sm->get('YourRegisteredErrorHandlerListener'), 100);
    }

    public function getConfig(){/*common code*/}
    public function getAutoloaderConfig(){/*common code*/}
}

Done, now your Module class is simplified ;)

About these ads

5 Responses

Subscribe to comments with RSS.

  1. ojhaujjwal said, on January 8, 2014 at 9:20 am

    Thanks for the post. I often use `Zend\EventManager\ListenerAggregateInterface`. Can you explain please the difference if any?

  2. Dennis said, on February 6, 2014 at 7:33 pm

    I also used to implement ListenerAggregateInterface. Then I created a AbstractAggregate just to note, that ZF2 comes with a build-in AbstractAggregate ;-)

    Look at this one: Zend\EventManager\AbstractListenerAggregate

    Extending this, you will save a few lines of code ;-)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 269 other followers

%d bloggers like this: