Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Notification Bundle Laravel Package

demroos/notification-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies

    composer require demroos/notification-bundle symfony/messenger
    
  2. Configure Messenger Update config/packages/messenger.yaml to define a transport (e.g., doctrine://default or sync://).

  3. Configure Notification Bundle Add notification.yml to config/packages/:

    notification:
        entities:
            - { name: "user", class: "App\Notification\UserNotification" }
        sender: "App\Services\CustomNotificationSender"
    
  4. 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 []; }
    }
    
  5. Set Up Controller Create NotificationController (as shown in README) and route it to handle incoming notifications.

  6. Send a Test Notification Use the NotificationSenderInterface to dispatch a notification:

    $sender = app()->make('notification.sender');
    $sender->send(new UserNotification());
    

Implementation Patterns

Core Workflow

  1. Outbound Notifications

    • Use NotificationSenderInterface to dispatch notifications (e.g., after user actions).
    • Example:
      $sender->send(new UserNotification([
          'event' => 'welcome',
          'user_id' => 123,
      ]));
      
    • Payload is automatically serialized and routed via Messenger.
  2. Inbound Notifications

    • Configure messenger.yaml to process messages (e.g., doctrine://default for async).
    • The NotificationController deserializes and routes messages to their respective handlers.
  3. Entity-Based Routing

    • Define entities in notification.yml to map payloads to classes (e.g., userUserNotification).
    • The bundle auto-instantiates the correct class based on the name field in the payload.
  4. Custom Sender Logic

    • Extend 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);
          }
      }
      

Integration Tips

  • 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.


Gotchas and Tips

Pitfalls

  1. Missing Messenger Transport

    • Error: Notifications fail silently if messenger.yaml is misconfigured.
    • Fix: Ensure a transport (e.g., doctrine://default) is defined and the worker is running.
  2. Entity Mismatch

    • Error: Payload’s name field doesn’t match any notification.yml entity.
    • Fix: Verify name in payload matches a configured entity (case-sensitive).
  3. Circular Dependencies

    • Error: NotificationController may fail if NotificationReceiverInterface isn’t properly bound.
    • Fix: Ensure the bundle is auto-discovered or manually register it in config/bundles.php.
  4. Payload Serialization

    • Error: Complex objects (e.g., Eloquent models) may not serialize correctly.
    • Fix: Use json_encode()-compatible payloads or implement __serialize() in your notification class.

Debugging

  • 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
    

Extension Points

  1. 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;
        }
    }
    
  2. 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());
        }
    }
    
  3. 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);
        }
    }
    

Configuration Quirks

  • 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'
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui