open-solid / messenger
Simple Messenger Component
Requires
- php: >=8.2
- psr/container: ^2.0
- psr/log: ^3.0
- symfony/service-contracts: ^3.4
Requires (Dev)
- doctrine/orm: ^3.1
- phpunit/phpunit: ^10.0
- psalm/plugin-phpunit: ^0.18
- symfony/dependency-injection: ^7.0
- vimeo/psalm: ^5.0
README
Installation
First things first, you need to add Simple Messenger to your project. Open your terminal and type in:
composer require open-solid/messenger
Usage
Sending Messages with the Bus
Think of the "bus" as a mail delivery system for your messages. It follows a specific path, decided by some rules (middleware), to send your messages.
Here's a snippet on how to set it up and send a message:
use App\Message\MyMessage; use OpenSolid\Messenger\Bus\NativeMessageBus; use OpenSolid\Messenger\Handler\HandlersLocator; use OpenSolid\Messenger\Middleware\HandlerMiddleware; // This is your custom function that does something when a message arrives. $handler = function (MyMessage $message): mixed { // Do stuff with the message here... }; // Setting up the bus with a middleware that knows who handles the message. $bus = new NativeMessageBus([ new HandlerMiddleware(new HandlersLocator([ MyMessage::class => [$handler], // Match messages to handlers. ])), ]); // Send a message using the bus. $bus->dispatch(new MyMessage());
Handling Messages
A "message handler" is what does the work when a message arrives. It can be a simple function or a method in a class. Here's how you set one up:
use App\Message\MyMessage; class MyMessageHandler { public function __invoke(MyMessage $message): mixed { // Process the message here... } }
Middleware Magic
Middleware are helpers that do stuff before and after your message is handled. They can change the message or do other tasks.
Here’s how to create one:
use OpenSolid\Messenger\Middleware\Middleware; use OpenSolid\Messenger\Model\Envelope; class MyMiddleware implements Middleware { public function handle(Envelope $envelope, callable $next): void { // Do something before the message handler works. $next($envelope); // Pass the message along. // Do something after the message handler is done. } }
Framework Integration
- cqs-bundle - Symfony bundle for Command-Query buses.
- domain-event-bundle - Symfony bundle for Event bus.
License
This tool is available under the MIT License, which means you can use it pretty freely in your projects.