PHP code example of ashleydawson / domain-event-dispatcher

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

    

ashleydawson / domain-event-dispatcher example snippets




namespace Acme\Event;

class MyEvent
{
}



namespace Acme\EventListener;

use Acme\Event\MyEvent;

class MyTypedEventListener
{
    // Domain event listeners must implement the __invoke() magic method with only one argument
    public function __invoke(MyEvent $event)
    {
        // Do something useful here...
    }
}



shleyDawson\DomainEventDispatcher\DomainEventDispatcher;
use Acme\Event\MyEvent;
use Acme\EventListener\MyTypedEventListener;

// Add your listener to the dispatcher
DomainEventDispatcher::getInstance()->addListener(
    new MyTypedEventListener()
);

// Dispatch the event from within your domain, e.g. from your domain model, etc.
DomainEventDispatcher::getInstance()->dispatch(
    new MyEvent()
);



namespace Acme\EventListener;

class MyEventGeneralListener
{
    // Event is not type hinted as this is a general event listener - it will be invoked by all events
    public function __invoke($event)
    {
        // Do something useful here...
    }
}



namespace Acme\EventListener;

use Acme\Event\MyEvent;

class MyEventGeneralListener
{
    // This listener will only respond to MyEvent events
    public function __invoke(MyEvent $event)
    {
        // Do something useful here...
    }
}



shleyDawson\DomainEventDispatcher\DomainEventDispatcher;
use Acme\Event\MyEvent;
use Acme\EventListener\MyTypedEventListener;

// Add your listener to the dispatcher
DomainEventDispatcher::getInstance()->addListener(
    new MyTypedEventListener()
);

// Dispatch the event from within your domain, e.g. from your domain model, etc.
DomainEventDispatcher::getInstance()->defer(
    new MyEvent()
);

// From a different level of the application, dispatch the deferred events
DomainEventDispatcher::getInstance()->dispatchDeferred();



namespace Acme\DomainEventStorage;

use AshleyDawson\DomainEventDispatcher\EventStorage\EventStoreInterface;

class InMemoryEventStore implements EventStoreInterface
{
    private $events = [];

    public function append($event)
    {
        $this->events[] = $event;
    }
}



use AshleyDawson\DomainEventDispatcher\DomainEventDispatcher;
use Acme\DomainEventStorage\InMemoryEventStore;

DomainEventDispatcher::getInstance()->setEventStore(
    new InMemoryEventStore()
);



namespace Acme\Event;

use AshleyDawson\DomainEventDispatcher\EventStorage\DisposableEventInterface;

class MyDisposableEvent implements DisposableEventInterface
{
}

$ php bin/phpunit