PHP code example of purpleharmonie / event-system

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

    

purpleharmonie / event-system example snippets


use Purpleharmonie\EventSystem\EventDispatcher;
use Purpleharmonie\EventSystem\ListenerProvider;

// Create the listener provider and event dispatcher
$listenerProvider = new ListenerProvider();
$eventDispatcher = new EventDispatcher($listenerProvider);

// Define an event
class UserRegisteredEvent
{
    public function __construct(public string $username) {}
}

// Add a listener
$listenerProvider->addListener(UserRegisteredEvent::class, function(UserRegisteredEvent $event) {
    echo "User registered: {$event->username}\n";
});

// Dispatch an event
$event = new UserRegisteredEvent('john_doe');
$eventDispatcher->dispatch($event);

use Purpleharmonie\EventSystem\Interface\EventSubscriberInterface;

class UserSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            UserRegisteredEvent::class => [
                ['onUserRegistered', 10],
                ['sendWelcomeEmail', 5]
            ]
        ];
    }

    public function onUserRegistered(UserRegisteredEvent $event): void
    {
        echo "User registered: {$event->username}\n";
    }

    public function sendWelcomeEmail(UserRegisteredEvent $event): void
    {
        echo "Sending welcome email to {$event->username}\n";
    }
}

// Usage
$listenerProvider->addSubscriber(new UserSubscriber());

$listenerProvider->addListener(ExampleEvent::class, function(ExampleEvent $event) {
    echo "High priority listener\n";
}, 10);

$listenerProvider->addListener(ExampleEvent::class, function(ExampleEvent $event) {
    echo "Low priority listener\n";
}, -10);

use Purpleharmonie\EventSystem\StoppableEvent;

class StoppableExampleEvent extends StoppableEvent
{
    public $message;

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

$listenerProvider->addListener(StoppableExampleEvent::class, function(StoppableExampleEvent $event) {
    echo "First listener\n";
    $event->stopPropagation();
});

$listenerProvider->addListener(StoppableExampleEvent::class, function(StoppableExampleEvent $event) {
    echo "This won't be called if propagation is stopped\n";
});

use Purpleharmonie\EventSystem\Interface\ValidatableEventInterface;

class UserRegisteredEvent implements ValidatableEventInterface
{
    public function __construct(public string $username, public string $email) {}

    public function isValid(): bool
    {
        return !empty($this->username) && filter_var($this->email, FILTER_VALIDATE_EMAIL);
    }
}

// Add a custom validator
$eventDispatcher->addValidator(UserRegisteredEvent::class, function(UserRegisteredEvent $event) {
    return strlen($event->username) >= 3;
});

$eventDispatcher->addMiddleware(function($event) {
    if ($event instanceof UserRegisteredEvent) {
        $event->username = strtolower($event->username);
    }
    return $event;
});

$conditionalDispatcher = new ConditionalEventDispatcher($eventDispatcher);
$conditionalDispatcher->addCondition(UserRegisteredEvent::class, function(UserRegisteredEvent $event) {
    return strlen($event->username) > 3;
});

use Purpleharmonie\EventSystem\Interface\AsyncEventDispatcherInterface;

class ExampleAsyncDispatcher implements AsyncEventDispatcherInterface
{
    public function dispatchAsync(object $event, array $context = [])
    {
        // Queue the event for asynchronous processing
        return uniqid('job_');
    }

    public function getAsyncStatus($jobIdentifier): string
    {
        // Check and return the status of the async job
    }
}

$asyncDispatcher = new ExampleAsyncDispatcher();
$eventDispatcher->setAsyncDispatcher($asyncDispatcher);

// Dispatch asynchronously
$jobId = $eventDispatcher->dispatchAsync($event, ['source' => 'web_signup']);

// services.php
$services->set('example_subscriber', ExampleSubscriber::class)
    ->asGlobal(true)
    ->asShared(true);

$services->set('logger', function ($container) {
    return new Logger('event_dispatcher');
})
->implements(LoggerInterface::class)
->asGlobal(true)
->asShared(true);

$services->set('listener_provider', function ($container) {
    $logger = $container->get('logger');
    return new ListenerProvider($logger);
})
->implements(ListenerProviderInterface::class)
->asGlobal(true)
->asShared(true);

$services->set('event_dispatcher', EventDispatcher::class)
    ->autowire()
    ->asGlobal(true)
    ->asShared(true);