dependencies - How can I attach listeners to a service without modifying the service factory for each listener? -


i have simple class i've put inside module mail's service configuration.

'factories' => array(     'mailer' => function (servicelocatorinterface $sl) {         return new \project\mail\mailer();     } ) 

now, mailer uses eventmanager trigger events. i'd attach listener class log error whenever mailer failed sending email, i'd without modifying mailer every time have new listener attach.

how can setup mailer class listeners can attached other modules?

you'll have identify first mean "mailer fails sending email". if can check condition within mailer class must trigger corresponding mail.error or similar event.

then have attach listener eventmanager inside of mailer listen mail.error event , log error.

triggering error within mailer

let's assume our mailer class looks this:

<?php namespace project\mail;  class mailer {     const event_mail_error = 'mail.error';      protected $events;      public function seteventmanager(eventmanagerinterface $events)     {         $this->events = $events;         return $this;     }      public function geteventmanager()     {         if ($this->events === null)         {             $this->seteventmanager(new eventmanager);         }         return $this->events;     }      public function send(messageinterface $msg)     {         // try sending message. uh-oh failed!         if ($someerrorcondition)         {             $this->geteventmanager()->trigger(self::event_mail_error, $this, array(                 'custom-param' => 'failure reason',             ));         }     } } 

listening event

during bootstrap attach listener(s) eventmanager within mailer.

<?php namespace foobar;  use zend\eventmanager\event; use zend\mvc\mvcevent;  class module {     public function onbootstrap(mvcevent $event)     {         $application = $event->getapplication();         $services = $application->getservicemanager();         $mailer = $services->get('mailer');          $mailer->geteventmanager()->attach(mailer::event_mail_error, function(event $event)         {             $param = $event->getparam('custom-param');             // log error         });     } } 

please refer documentation on eventmanager implementation details.

i hope solves problem!


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -