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

sonata-project/notification-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require sonata-project/notification-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Sonata\NotificationBundle\SonataNotificationBundle::class => ['all' => true],
    ];
    
  2. Database Setup Run migrations (check vendor/sonata-project/notification-bundle/src/Resources/doc/index.md for schema):

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Notification Create a notification class (e.g., src/Notification/ExampleNotification.php):

    namespace App\Notification;
    
    use Sonata\NotificationBundle\Model\NotificationInterface;
    
    class ExampleNotification implements NotificationInterface
    {
        public function getSubject(): string
        {
            return 'Hello!';
        }
    
        public function getMessage(): string
        {
            return 'This is your first notification.';
        }
    }
    
  4. Send a Notification Inject Sonata\NotificationBundle\Model\NotificationManagerInterface and use:

    $notification = new ExampleNotification();
    $notificationManager->send($notification, $recipientUser);
    

Where to Look First

  • Configuration: config/packages/sonata_notification.yaml (auto-generated).
  • Doctrine Entities: vendor/sonata-project/notification-bundle/src/Resources/doc/index.md for schema.
  • Default Notifications: vendor/sonata-project/notification-bundle/src/Notification/ for built-in templates.
  • Twig Templates: vendor/sonata-project/notification-bundle/Resources/views/ for email/notification layouts.

First Use Case: Sending an Email Notification

  1. Extend AbstractNotification (recommended):
    use Sonata\NotificationBundle\Notification\AbstractNotification;
    
    class WelcomeNotification extends AbstractNotification
    {
        protected $subject = 'Welcome!';
        protected $message = 'Thanks for joining!';
    
        public function getRecipient(): ?UserInterface
        {
            return $this->getParameter('recipient'); // Set via send() method
        }
    }
    
  2. Send it:
    $notification = new WelcomeNotification();
    $notification->setParameter('recipient', $user);
    $notificationManager->send($notification);
    

Implementation Patterns

Core Workflows

1. Creating Custom Notifications

  • Extend AbstractNotification for reusable templates:
    class OrderConfirmationNotification extends AbstractNotification
    {
        protected $subject = 'Your order #%order_id% is confirmed';
        protected $message = 'Thank you for your purchase!';
    
        public function getRecipient(): ?UserInterface
        {
            return $this->getParameter('customer');
        }
    
        public function getParameters(): array
        {
            return [
                'order_id' => $this->getParameter('order_id'),
            ];
        }
    }
    
  • Override methods:
    • getSubject()/getMessage() for dynamic content.
    • getRecipient() to define who receives the notification.
    • getParameters() to pass data to Twig templates.

2. Sending Notifications

  • Basic send:
    $notification = new CustomNotification();
    $notification->setParameter('key', 'value');
    $notificationManager->send($notification, $recipientUser);
    
  • Bulk send:
    $users = $userRepository->findByRole('admin');
    foreach ($users as $user) {
        $notificationManager->send($notification, $user);
    }
    
  • Async send (via Symfony Messenger):
    $notificationManager->sendAsync($notification, $recipientUser);
    

3. Using Twig Templates

  • Place custom templates in templates/sonata_notification/ (e.g., email.html.twig).
  • Extend base templates:
    {% extends '@SonataNotification/email.html.twig' %}
    
    {% block subject %}
        {{ parent() }} - Custom Subject
    {% endblock %}
    

4. Integrating with Events

  • Listen for sonata.notification.send event to modify notifications:
    $eventDispatcher->addListener('sonata.notification.send', function (NotificationEvent $event) {
        $event->getNotification()->setSubject('[URGENT] ' . $event->getNotification()->getSubject());
    });
    

5. Scheduling Notifications

  • Use Symfony’s CronTrigger or SingleMessage for delayed sends:
    $message = new SendNotificationMessage($notification, $recipient);
    $bus->dispatch($message);
    

Integration Tips

Laravel-Specific Adaptations

  1. Service Container Integration Bind the notification manager in config/services.php:

    'SonataNotificationBundle' => [
        'notification_manager' => \Sonata\NotificationBundle\Model\NotificationManager::class,
    ],
    

    Resolve it in Laravel:

    $notificationManager = app('SonataNotificationBundle.notification_manager');
    
  2. Laravel Events Convert Symfony events to Laravel:

    Event::listen('sonata.notification.send', function ($event) {
        // Laravel logic here
    });
    
  3. Laravel Mail Integration Override the transporter to use Laravel’s Mailer:

    $notification->setTransporter(new LaravelMailTransporter(app('mailer')));
    
  4. Laravel Queues Use Laravel queues for async sends:

    $notificationManager->sendAsync($notification, $user)
        ->setQueue('notifications');
    

Common Integrations

  • Doctrine ORM: Works out-of-the-box; ensure Notification entity is mapped.
  • Sonata Admin: Use sonata.notification.admin to manage notifications via UI.
  • API Platform: Expose notifications as API resources:
    # config/api_platform/resources.yaml
    Sonata\NotificationBundle\Entity\Notification:
        collectionOperations:
            get: ~
        itemOperations:
            get: ~
    

Gotchas and Tips

Pitfalls

  1. Database Schema Mismatch

    • Issue: Running migrations without checking the schema first may corrupt your database.
    • Fix: Always review vendor/sonata-project/notification-bundle/src/Resources/doc/index.md before migrating.
    • Laravel Note: Use Laravel Migrations to adapt the schema:
      php artisan make:migration create_notifications_table --table=notification
      
  2. Circular Dependencies in Notifications

    • Issue: Notifications referencing each other (e.g., A triggers B, which triggers A again) can cause infinite loops.
    • Fix: Add a sent_at check or use a NotificationSent event to track sent notifications.
  3. Transporter Configuration

    • Issue: Forgetting to configure the transporter (e.g., Swiftmailer) results in silent failures.
    • Fix: Explicitly set the transporter:
      $notification->setTransporter($container->get('sonata.notification.transporter.mail'));
      
  4. Recipient Validation

    • Issue: Sending notifications to non-existent users may throw errors.
    • Fix: Validate recipients:
      if (!$recipientUser || !$recipientUser->isEnabled()) {
          throw new \RuntimeException('Invalid recipient');
      }
      
  5. Async Send Quirks

    • Issue: Async sends may fail silently if the queue worker crashes.
    • Fix: Implement a retry mechanism or monitor failed jobs:
      $notificationManager->sendAsync($notification, $user)
          ->setRetryDelay(300); // 5 minutes
      

Debugging Tips

  1. Enable Debug Mode Set sonata_notification.debug: true in config to log sent notifications:

    sonata_notification:
        debug: true
    
  2. Check the Notification Log Query the notification table for sent/not-sent records:

    SELECT * FROM notification WHERE recipient_id = ? AND sent_at IS NULL;
    
  3. Twig Debugging Dump template variables:

    {% dump notification.parameters %}
    
  4. Event Listener Debugging Log events to understand the flow:

    $eventDispatcher->addListener('sonata.notification.send', function (NotificationEvent $event) {
        \Log::debug('Notification sent', ['subject' => $event->getNotification()->getSubject()]);
    });
    

Configuration Quirks

  1. Default Transporter
    • The bundle defaults to Swiftmailer. To use Laravel’s Mail:
      sonata_notification:
          transporter:
              mail:
                  service: sonata.notification.transporter.mail
                  from_email: 'no-reply@example.com'
      
    • Create a custom
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware