PHP code example of nimbly / announce

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

    

nimbly / announce example snippets


namespace App\Events;

use App\Models\User;
use Nimbly\Announce\Event;

class UserRegisteredEvent extends StoppableEvent
{
	public function __construct(public User $user)
	{
	}
}

namespace App\Subscribers;

use App\Events\UserRegisteredEvent;
use App\Services\EmailService;
use Nimbly\Announce\Subscribe;

class EmailSubscriber
{
	#[Subscribe(UserRegisteredEvent::class)]
	public function onUserRegistered(
		UserRegisteredEvent $event,
		EmailService $emailService): void
	{
		$emailService->send("registration_email", $event->user->email);
	}
}

$dispatcher = new Dispatcher(
	subscribers: [
		EmailSubscriber::class,
		new FooSubscriber,
	],
	container: $container
);

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

class EmailSubscriber
{
	#[Subscribe(UserRegisteredEvent::class)]
	public function onUserRegistered(
		UserRegisteredEvent $event,
		EmailService $emailService): void
	{
		$emailService->send("registration_email", $event->user->email);

		// Prevent any further handlers from processing this event
		$event->stop();
	}
}

$dispatcher = new Dispatcher;
$dispatcher->listen(
	UserRegisteredEvent::class,
	function(UserRegisteredEvent $event): void {
		// do some event stuff
	}
);

$dispatcher = new Dispatcher;
$dispatcher->listen(
	"*",
	function($event): void {
		// Respond to all events...
	}
);