Install Dependencies
composer require demroos/notification-bundle symfony/messenger
Configure Messenger
Update config/packages/messenger.yaml to define a transport (e.g., doctrine://default or sync://).
Configure Notification Bundle
Add notification.yml to config/packages/:
notification:
entities:
- { name: "user", class: "App\Notification\UserNotification" }
sender: "App\Services\CustomNotificationSender"
Create a Notification Class
Implement NotificationInterface (e.g., UserNotification):
namespace App\Notification;
use Demroos\NotificationBundle\Notification\NotificationInterface;
class UserNotification implements NotificationInterface {
public function getEntityName(): string { return "user"; }
public function getPayload(): array { return []; }
}
Set Up Controller
Create NotificationController (as shown in README) and route it to handle incoming notifications.
Send a Test Notification
Use the NotificationSenderInterface to dispatch a notification:
$sender = app()->make('notification.sender');
$sender->send(new UserNotification());
Outbound Notifications
NotificationSenderInterface to dispatch notifications (e.g., after user actions).$sender->send(new UserNotification([
'event' => 'welcome',
'user_id' => 123,
]));
Inbound Notifications
messenger.yaml to process messages (e.g., doctrine://default for async).NotificationController deserializes and routes messages to their respective handlers.Entity-Based Routing
entities in notification.yml to map payloads to classes (e.g., user → UserNotification).name field in the payload.Custom Sender Logic
NotificationSenderInterface to add pre-processing (e.g., logging, validation):
class CustomNotificationSender implements NotificationSenderInterface {
public function send(NotificationInterface $notification) {
// Custom logic (e.g., rate limiting)
$this->dispatchMessage($notification);
}
}
Event-Driven Triggers
Attach notifications to Laravel events (e.g., user.registered):
Event::listen(UserRegistered::class, function ($event) {
$sender->send(new UserNotification(['event' => 'registered', 'user_id' => $event->user->id]));
});
Queue Workers Use Symfony Messenger’s workers to process notifications asynchronously:
php bin/console messenger:consume async -vv
Testing
Mock NotificationSenderInterface in tests:
$sender = Mockery::mock(NotificationSenderInterface::class);
$sender->shouldReceive('send')->once();
Payload Validation
Validate payloads in NotificationInterface::getPayload() or via a custom sender.
Missing Messenger Transport
messenger.yaml is misconfigured.doctrine://default) is defined and the worker is running.Entity Mismatch
name field doesn’t match any notification.yml entity.name in payload matches a configured entity (case-sensitive).Circular Dependencies
NotificationController may fail if NotificationReceiverInterface isn’t properly bound.config/bundles.php.Payload Serialization
json_encode()-compatible payloads or implement __serialize() in your notification class.Log Notifications
Add a logger to messenger.yaml to track failed messages:
messenger:
transports:
async: '%env(MESSENGER_TRANSPORT_DSN)%'
failure_transport: failed
transports:
failed: 'doctrine://default'
routing:
'Demroos\NotificationBundle\Message\NotificationMessage': async
Check Worker Logs
Run workers with -vv for verbose output:
php bin/console messenger:consume async -vv
Custom Message Classes
Extend Demroos\NotificationBundle\Message\NotificationMessage to add metadata:
class CustomNotificationMessage extends NotificationMessage {
public function __construct(array $payload, string $entityName, string $customField) {
parent::__construct($payload, $entityName);
$this->customField = $customField;
}
}
Dynamic Entity Routing
Override NotificationReceiverInterface to dynamically resolve entities:
class CustomNotificationReceiver implements NotificationReceiverInterface {
public function handleRequest(Request $request) {
$entityName = $request->request->get('dynamic_entity');
// Logic to resolve class dynamically
return new $className($request->request->all());
}
}
Middleware for Notifications
Add middleware to the NotificationController to validate/authenticate requests:
class NotificationAuthMiddleware implements MiddlewareInterface {
public function handle(Request $request, callable $next) {
if (!$request->headers->has('X-Notification-Token')) {
throw new \RuntimeException('Invalid token');
}
return $next($request);
}
}
Case Sensitivity
notification.yml entity name fields are case-sensitive. Ensure consistency with payload data.
Default Channel
Incoming notifications default to the notifications channel. Override in messenger.yaml if needed:
messenger:
transports:
notifications: 'doctrine://default'
How can I help you explore Laravel packages today?