Zend Framework 2 : Move out your listeners from Module class

来源:互联网 发布:美丽折淘宝客辅助器 编辑:程序博客网 时间:2024/06/05 23:03
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 ;)

0 0