PHP Classes

File: Dispatcher.php

Recommend this page to a friend!
  Classes of Yelson Ramirez Grönroos   PHP Event Dispatcher Class   Dispatcher.php   Download  
File: Dispatcher.php
Role: Class source
Content type: text/plain
Description: Class source
Class: PHP Event Dispatcher Class
Call registered handlers when an event triggers
Author: By
Last change:
Date: 6 years ago
Size: 1,527 bytes
 

Contents

Class file image Download
<?php
declare(strict_types=1);


namespace
App;

/**
 * Event Dispatcher
 */
class Dispatcher
{
   
/**
     * Listeners
     *
     * @var array
     */
   
protected $listeners = [];

   
/**
     * getListeners(), returns ALL added listeners.
     *
     * @return array
     */
   
public function getListeners() : array
    {
        return
$this->listeners;
    }

   
/**
     * Add a single listener i.e: $dispatcher->addListener(EventName, new Path\To\Your\Listener())
     *
     * @param string $name
     * @param Listener $listener
     * @return void
     */
   
public function addListener(string $name, Listener $listener) : void
   
{
       
$this->listeners[$name][] = $listener;
    }
   
   
/**
     * Retrieves all listeners listed under the listener @param string $name
     *
     * @param string $name
     * @return array
     */
   
public function getListenersByEvent(string $name) : array
    {
        if (!
$this->hasListeners($name)) {
            return [];
        }

        return
$this->listeners[$name];
    }

   
/**
     * Checks whether the requested listener exists or not, otherwise returns false.
     *
     * @param string $name
     * @return boolean
     */
   
public function hasListeners(string $name) : bool
   
{
        return isset(
$this->listeners[$name]);
    }

   
/**
     * Retrieves listeners through $this->getListenersByEvent(string $name), iterates through them.
     * Instance @param Event $event will be passed into the method.
     *
     * @param Event $event
     * @return void
     */
   
public function dispatch(Event $event) : void
   
{
        foreach (
$this->getListenersByEvent($event->getName()) as $listener) {
           
$listener->handle($event);
        }
    }
}