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

Sonata Notification Bundle Laravel Package

awaresoft/sonata-notification-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require awaresoft/sonata-notification-bundle
    

    Ensure your config/bundles.php includes:

    return [
        // ...
        Awaresoft\SonataNotificationBundle\AwaresoftSonataNotificationBundle::class => ['all' => true],
    ];
    
  2. Database Migration: Run the bundle's migration to create the required tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Notification: Use the NotificationManager service to send a basic notification:

    use Awaresoft\SonataNotificationBundle\Manager\NotificationManager;
    
    $notificationManager = $this->container->get('sonata.notification.manager');
    $notificationManager->send(
        'user@example.com', // Recipient
        'Welcome!',          // Subject
        'Hello, thanks for signing up!' // Message
    );
    
  4. Configuration: Override default settings in config/packages/awaresoft_sonata_notification.yaml:

    awaresoft_sonata_notification:
        default_from_email: 'noreply@example.com'
        transport: 'mailer' # or 'swiftmailer', 'sendmail', etc.
    

Implementation Patterns

Core Workflows

1. Sending Notifications

  • Basic Email:
    $notificationManager->send(
        'user@example.com',
        'Your Order Confirmation',
        'Your order #12345 has been processed.'
    );
    
  • With Template: Use Twig templates for dynamic content:
    $notificationManager->sendTemplate(
        'user@example.com',
        'emails/order_confirmation.twig',
        ['order' => $order]
    );
    

2. Queued Notifications

Dispatch notifications asynchronously using Symfony Messenger:

use Awaresoft\SonataNotificationBundle\Message\SendNotificationMessage;

$message = new SendNotificationMessage(
    'user@example.com',
    'Welcome!',
    'Thanks for joining!'
);
$this->messageBus->dispatch($message);

3. User-Specific Notifications

Attach metadata (e.g., user ID, locale) for personalized delivery:

$notificationManager->send(
    'user@example.com',
    'Your Reminder',
    'Don’t forget your appointment tomorrow!',
    ['user_id' => 42, 'locale' => 'en_US']
);

4. Bulk Notifications

Send to multiple recipients efficiently:

$recipients = ['user1@example.com', 'user2@example.com'];
$notificationManager->sendBulk($recipients, 'Newsletter', 'Check this out!');

Integration Tips

Symfony Events

Trigger notifications on user actions (e.g., registration, order placement):

// In your event subscriber
public function onUserRegistered(UserRegisteredEvent $event)
{
    $this->notificationManager->send(
        $event->getUser()->getEmail(),
        'Account Created',
        'Your account is now active!'
    );
}

Custom Transport

Extend the bundle to support APIs (e.g., Twilio for SMS):

# config/packages/awaresoft_sonata_notification.yaml
awaresoft_sonata_notification:
    transports:
        sms:
            class: App\Notification\Transport\TwilioTransport
            options:
                account_sid: 'your_sid'
                auth_token: 'your_token'

Templates

Store templates in templates/emails/ and reference them:

{# templates/emails/welcome.twig #}
<h1>Welcome, {{ user.name }}!</h1>
<p>Your account was created on {{ 'now'|date('Y-m-d') }}.</p>

Testing

Mock the NotificationManager in PHPUnit:

$notificationManager = $this->createMock(NotificationManager::class);
$notificationManager->expects($this->once())
    ->method('send')
    ->with('user@example.com', 'Test', 'Message');
$this->container->set('sonata.notification.manager', $notificationManager);

Gotchas and Tips

Pitfalls

  1. Database Schema:

    • The bundle auto-generates tables (notification, notification_recipient). Ensure your migrations are up-to-date.
    • Fix: Run php bin/console doctrine:schema:update --force if tables are missing.
  2. Transport Configuration:

    • Defaults to Symfony Mailer. If using swiftmailer, ensure the bundle is installed:
      composer require symfony/mailer
      
    • Fix: Explicitly set transport in config:
      awaresoft_sonata_notification:
          transport: 'swiftmailer'
      
  3. Caching Issues:

    • After modifying the bundle (e.g., symlinked version), clear caches:
      php bin/console cache:clear
      php bin/console ca:cl
      
  4. Queue Stuck Jobs:

    • If using Messenger, monitor failed jobs:
      php bin/console messenger:failed:list
      php bin/console messenger:failed:remove <id>
      

Debugging Tips

  1. Log Notifications: Enable logging in config/packages/monolog.yaml:

    handlers:
        sonata_notification:
            type: stream
            path: "%kernel.logs_dir%/sonata_notification.log"
            level: debug
    
  2. Check Recipients: Verify recipients are correctly formatted (no typos, valid emails).

  3. Template Errors:

    • Ensure Twig templates extend a base layout (e.g., emails/base.html.twig).
    • Fix: Wrap templates in:
      {% extends 'emails/base.html.twig' %}
      {% block body %}{% endblock %}
      

Extension Points

  1. Custom Notification Types: Extend the Notification entity to add fields (e.g., is_read, priority):

    // src/Entity/ExtendedNotification.php
    use Awaresoft\SonataNotificationBundle\Entity\Notification as BaseNotification;
    
    class ExtendedNotification extends BaseNotification
    {
        private $priority;
        // ...
    }
    
  2. Override Services: Replace the NotificationManager with a custom class:

    # config/services.yaml
    services:
        App\Notification\CustomNotificationManager:
            decorates: 'sonata.notification.manager'
            arguments: ['@.inner']
    
  3. Add Transport: Implement Awaresoft\SonataNotificationBundle\Transport\TransportInterface:

    class SlackTransport implements TransportInterface
    {
        public function send(Notification $notification): void
        {
            // Send to Slack webhook
        }
    }
    

    Register it in config:

    awaresoft_sonata_notification:
        transports:
            slack:
                class: App\Notification\Transport\SlackTransport
    

Performance

  1. Batch Processing: For bulk notifications, use chunking to avoid memory issues:

    $notificationManager->sendBulkInChunks($recipients, 100, 'Newsletter', 'Content');
    
  2. Queue Workers: Scale Messenger workers for high-volume notifications:

    php bin/console messenger:consume async -vv
    
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
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