PHP code example of mitch / event-dispatcher

1. Go to this page and download the library: Download mitch/event-dispatcher 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/ */

    

mitch / event-dispatcher example snippets


  "  "mitch/event-dispatcher": "0.1.x"
  }
  

  php composer.phar update
  

  'Mitch\EventDispatcher\Laravel\EventDispatcherServiceProvider'
  

 namespace Domain\Accounts\Events;

use Mitch\EventDispatcher\Event;

class UserCreatedEvent implements Event
{
    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function getName()
    {
        return 'UserCreated';
    }
}

 namespace Domain\Accounts\EventListeners;

use Mitch\EventDispatcher\Listener;

class MailNewlyCreatedUserListener implements Listener
{
    private $mailer

    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public function handle(Event $event)
    {
        // Do something with the event
    }
}

use Mitch\EventDispatcher\Dispatcher;
use Domain\Accounts\Events\UserCreatedEvent;
use Domain\Accounts\EventListeners\MailNewlyCreatedUserListener;

// Listening for event
$mailer = // Some mail package...
$listener = new MailNewlyCreatedUserListener($mailer);

$dispatcher = new Dispatcher;
$dispatcher->addListener('UserCreated', $listener);

// Dispatching event
$user = // A wild user appeared..
$event = new UserCreatedEvent($user);

$dispatcher->dispatch($event);

use Mitch\EventDispatcher\Dispatcher;
use Domain\Accounts\UserAddedEvent;
use Domain\Achievements\UserGotAchievementEvent;

$user = ...;
$achievement = ...;
$events = [
    new UserAddedEvent($user),
    new UserGotAchievementEvent($user, $achievement)
];

$dispatcher = new Dispatcher;
$dispatcher->dispatch($events);