PHP code example of mildabre / event-dispatcher

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

    

mildabre / event-dispatcher example snippets




use Mildabre\EventDispatcher\Attributes\Event;

#[Event]
final readonly class UserRegistered
{
    public function __construct(
        public string $email,
        public \DateTimeImmutable $registeredAt,
    ) {}
}



use Mildabre\ServiceDiscovery\Attributes\EventListener;

#[EventListener]
class SendWelcomeEmail
{
    public function __construct(
        private EmailService $emailService,
    ) {}

    public function handle(UserRegistered $event): void
    {
        $this->emailService->sendWelcome($event->email);
    }
}



use Mildabre\EventDispatcher\EventDispatcher;

class UserService
{
    public function __construct(
        private EventDispatcher $eventDispatcher,
    ) {}

    public function register(string $email, string $password): void
    {
        // ... registration logic ...
        
        $this->eventDispatcher->dispatch(
            new UserRegistered($email, new \DateTimeImmutable())
        );
    }
}