PHP code example of remils / event-listener

1. Go to this page and download the library: Download remils/event-listener library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

remils / event-listener example snippets




use Remils\EventListener\AttachDispatcherInterface;
use Remils\EventListener\Dispatcher;
use Remils\EventListener\EventInterface;
use Remils\EventListener\ListenerInterface;
use Remils\EventListener\SubscriberInterface;

 SendEntityEvent implements EventInterface
{
}

class ResponseEntityEvent implements EventInterface
{
    public Entity $entity;
}

class EntitySubscriber implements SubscriberInterface, AttachDispatcherInterface
{
    protected Dispatcher $dispatcher;

    protected Entity $entity;

    public function __construct()
    {
        $this->entity = new Entity();
    }

    public function setDispatcher(Dispatcher $dispatcher): void
    {
        $this->dispatcher = $dispatcher;
    }

    public function getSubscribedEvents(): array
    {
        return [
            SetAgeEntityEvent::class => 'setAge',
            SetNameEntityEvent::class => 'setName',
            SendEntityEvent::class => 'sendEntity',
        ];
    }

    public function setAge(SetAgeEntityEvent $event): void
    {
        $this->entity->age = $event->age;
    }

    public function setName(SetNameEntityEvent $event): void
    {
        $this->entity->name = $event->name;
    }

    public function sendEntity(SendEntityEvent $event): void
    {
        $event = new ResponseEntityEvent();
        $event->entity = $this->entity;

        $this->dispatcher->dispatch($event);
    }
}

class ResponseEntityListener implements ListenerInterface
{
    public function getEventNamespace(): string
    {
        return ResponseEntityEvent::class;
    }

    /**
     * @param ResponseEntityEvent $event
     * @return void
     */
    public function handle(EventInterface $event): void
    {
        var_dump($event->entity);
    }
}

$listeners = [
    new EntitySubscriber(),
    new ResponseEntityListener(),
];

$dispatcher = new Dispatcher($listeners);

$event = new SetAgeEntityEvent();
$event->age = 64;

$dispatcher->dispatch($event);

$event = new SetNameEntityEvent();
$event->name = 'Анатолий';

$dispatcher->dispatch($event);

$event = new SendEntityEvent();

$dispatcher->dispatch($event);