Weave 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

Notifications Laravel Package

ibexa/notifications

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ibexa/notifications
    

    (Note: Requires Ibexa DXP as a dependency—install via Ibexa DXP docs)

  2. Configuration: Add to config/services.yaml (or equivalent Ibexa config):

    ibexa:
        notifier:
            channels:
                email:
                    transport: 'symfony://mailer.default'
                # Add other channels (e.g., 'push', 'sms')
    
  3. First Use Case: Trigger a notification via a service:

    use Ibexa\Notifications\Notification\Notification;
    use Ibexa\Notifications\Notification\NotificationFactory;
    
    $notificationFactory = app(NotificationFactory::class);
    $notification = $notificationFactory->create(
        'user.registered',
        ['user' => $userData]
    );
    $notification->send();
    

Key Entry Points

  • NotificationFactory: Create typed notifications (e.g., user.registered, content.published).
  • NotificationSender: Dispatch notifications to configured channels.
  • NotificationTemplateResolver: Override default templates per notification type.

Implementation Patterns

Core Workflow

  1. Define Notification Types: Extend Notification or use built-in types (e.g., SystemNotification, UserNotification).

    class CustomNotification extends Notification
    {
        public function __construct(
            public string $type,
            public array $context = []
        ) {}
    }
    
  2. Channel Integration: Register custom channels (e.g., Slack, Webhook) by implementing ChannelInterface:

    use Ibexa\Notifications\Channel\ChannelInterface;
    
    class SlackChannel implements ChannelInterface
    {
        public function send(Notification $notification): void
        {
            // Logic to send to Slack
        }
    }
    

    Bind in DI container:

    services:
        Ibexa\Notifications\Channel\SlackChannel: ~
    ibexa.notifier.channels.slack: '@SlackChannel'
    
  3. Dynamic Templates: Override templates via NotificationTemplateResolver:

    use Ibexa\Notifications\Template\NotificationTemplateResolver;
    
    class CustomTemplateResolver implements NotificationTemplateResolver
    {
        public function resolve(Notification $notification): string
        {
            return match ($notification->getType()) {
                'user.registered' => 'emails/user_registered.twig',
                default => 'emails/default.twig',
            };
        }
    }
    
  4. Event-Driven Triggers: Listen for Ibexa events (e.g., ContentPublishEvent) to dispatch notifications:

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class NotificationSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                'Ibexa\Content\Event\ContentPublishEvent' => 'onContentPublish',
            ];
        }
    
        public function onContentPublish(ContentPublishEvent $event): void
        {
            $notification = app(NotificationFactory::class)->create(
                'content.published',
                ['content' => $event->getContent()]
            );
            $notification->send();
        }
    }
    

Best Practices

  • Type Safety: Use enums or constants for notification types (e.g., NotificationType::USER_REGISTERED).
  • Queue Notifications: For async processing, wrap NotificationSender in a queue job:
    use Ibexa\Notifications\Notification\NotificationSender;
    
    class SendNotificationJob implements ShouldQueue
    {
        public function handle(NotificationSender $sender, Notification $notification)
        {
            $sender->send($notification);
        }
    }
    
  • Testing: Mock NotificationSender in unit tests:
    $sender = $this->createMock(NotificationSender::class);
    $sender->expects($this->once())->method('send');
    

Gotchas and Tips

Common Pitfalls

  1. Channel Configuration:

    • Issue: Forgetting to configure channels in ibexa.notifier.channels.
    • Fix: Ensure services.yaml includes all active channels (e.g., email, push).
    • Debug: Check ibexa.notifier.channel_manager for registered channels.
  2. Template Resolution:

    • Issue: Custom templates not overriding defaults.
    • Fix: Implement NotificationTemplateResolver and bind it as a service:
      services:
          Ibexa\Notifications\Template\CustomTemplateResolver: ~
      ibexa.notifier.template_resolver: '@CustomTemplateResolver'
      
  3. BC Breaks:

    • v5.0+: Config node renamed from notifications to notifier (see #8).
    • Symfony 7+: Requires symfony/mailer for email channels (added in #22).
  4. Async Delays:

    • Issue: Notifications not arriving due to queue failures.
    • Fix: Monitor queue workers and implement retries:
      $job->onQueue('notifications')->retryUntil(3600); // Retry for 1 hour
      

Debugging Tips

  • Log Notifications: Decorate NotificationSender to log sent notifications:

    class LoggingNotificationSender implements NotificationSender
    {
        public function __construct(private NotificationSender $decorated) {}
    
        public function send(Notification $notification): void
        {
            \Log::info('Sent notification', ['type' => $notification->getType()]);
            $this->decorated->send($notification);
        }
    }
    
  • Validate Payloads: Use Notification::assertValid() to catch malformed data early:

    $notification = $factory->create('invalid.type');
    $notification->assertValid(); // Throws \InvalidArgumentException
    

Extension Points

  1. Custom Channels: Extend AbstractChannel for reusable logic (e.g., rate limiting, retry logic).

  2. Notification Metadata: Add metadata via Notification::setMetadata(['key' => 'value']) for tracking.

  3. Template Inheritance: Use Twig’s {% extends %} in custom templates to inherit from Ibexa’s base templates.

  4. Testing: Stub NotificationSender in PHPUnit:

    $sender = $this->createMock(NotificationSender::class);
    $sender->method('send')->willReturnCallback(fn($n) => $this->assertEquals('user.registered', $n->getType()));
    
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.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel