Zend Framework 2 : Move out your listeners from Module class

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 ;)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值