Last Updated: February 25, 2016
·
469
· mishak87

4 things never to do when using events

Never mix logic! business and low level events
Be consistent!

Never terminate! code
Be alive!

Never throw! exception
Be quiet!

Never depend on order or others! in which handler is called
Be independent!

Handler for each event should be independent of other handlers registered to that event.

If you need to redirect or break in events use chain of responsibility, priority queue, ordered queue or something more suitable instead. Or delegate such actions to other services that will execute them in appropriate time.

$redirector = new Redirector;
$object->event[] = function () use ($redirector) {
    $redirector->redirect('...');
};
// before sending templates
$redirector->perform();
class Redirector // redirects to url with highest priority
{
    private $priority = -1;
    private $url = '';
    function redirect($url, $priority = 0) {
        if ($this->priority > $priority) {
            $this->priority = $priority;
            $this->url = $url;
        }
    }
    function perform() {
        if ($this->url !== null) {
            header('Location: ' . $this->url);
            die;
        }
    }
};