PHP code example of mattferris / events

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

    

mattferris / events example snippets


namespace MyDomain;

class DomainEvents extends \MattFerris\Events\AbstractDomainEvents
{
}

namespace MyDomain;

class SomeEvent extends MattFerris\Events\Event
{
    protected $someArgument;

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

    public function getSomeArgument()
    {
        return $this->someArgument;
    }
}

namespace MyDomain;

class SomeEntity
{
    public function doSomething()
    {
        // stuff happens

        // dispatch event
        DomainEvents::dispatch(new SomeEvent($argument));
    }
}

$dispatcher = new MattFerris\Events\Dispatcher();
MyDomain\DomainEvents::setDispatcher($dispatcher);

$dispatcher->addListener('MyDomain.SomeEvent', function ($event) { ... });

// listen for all events in the `MyDomain` namespace
$dispatcher->addListener('MyDomain.', $handler);

// listen for all SomeEvent events in any domain
$dispatcher->addListener('.SomeEvent', $handler);

// listen for all events
$dispatcher->addListener('*', $handler);

$dispatcher->addListener('foo.bar', $listener);

$dispatcher->dispatch($event, 'foo.bar');

// give the listener the highest priority
$dispatcher->addListener('*', $listener, 0);

// alternatively, you can use the priority constant
$dispatcher->addListener('*', $listener, Dispatcher::PRIORITY_HIGH);

use MattFerris\Provider\ProviderInterface;
use MattFerris\Provider\ConsumerInterface;

class EventProvider implements ProviderInterface
{
    public function provides(ConsumerInterface $dispatcher)
    {
        $dispatcher->addListener('*', $listener);
        ...
    }
}

$logger = new MattFerris\Events\Logger($dispatcher, function ($msg) { error_log($msg); });

$logger->setPrefix('another prefix: ');

namespace MyDomain;

class DomainEventLoggerHelpers extends MattFerris\Events\AbstractDomainEventLoggerHelpers
{
    static public function onSomeEvent(SomeEvent $e)
    {
        $foo = $e->getFoo();
        $bar = $e->getBar();

        return "SomeEvent was dispatched with values foo=$foo, bar=$bar";
    }
}

MyDomain\DomainEventLoggerHelepers::addHelpers($logger);