PHP code example of sugiphp / events

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

    

sugiphp / events example snippets


use SugiPHP\Events\Dispatcher;
use SugiPHP\Events\ListenerProvider;

$provider = new ListenerProvider();
$provider->addListener(UserRegistered::class, function (UserRegistered $event) {
    // send a welcome email, etc.
});

$dispatcher = new Dispatcher($provider);

$event = new UserRegistered($user);
$dispatcher->dispatch($event);

$provider->addListener(UserRegistered::class, new SendWelcomeEmail());
$provider->addListener(UserRegistered::class, [$logger, 'logRegistration']);
$provider->addListener(UserRegistered::class, 'notify_admins');

interface DomainEvent {}
class UserRegistered implements DomainEvent {}

// Fires for UserRegistered and any other DomainEvent implementation.
$provider->addListener(DomainEvent::class, $auditLogger);

use Psr\EventDispatcher\StoppableEventInterface;

class UserRegistered implements StoppableEventInterface
{
    private bool $stopped = false;

    public function isPropagationStopped(): bool
    {
        return $this->stopped;
    }

    public function stopPropagation(): void
    {
        $this->stopped = true;
    }
}

use SugiPHP\Events\Dispatcher;
use SugiPHP\Events\EventDispatcherTrait;
use Psr\EventDispatcher\EventDispatcherInterface;

class UserService implements EventDispatcherInterface
{
    use EventDispatcherTrait;
}

$service = new UserService();
$service->setEventDispatcher(new Dispatcher($provider));
$service->dispatch(new UserRegistered($user));