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

Bdf Event Notifier Laravel Package

b2pweb/bdf-event-notifier

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require b2pweb/bdf-event-notifier
    

    Publish the config file (if available):

    php artisan vendor:publish --provider="B2PWeb\BDFEventNotifier\BDFEventNotifierServiceProvider"
    
  2. Basic Configuration Check config/bdf-event-notifier.php for default settings (e.g., default channels, retry logic, or logging). Override as needed:

    'channels' => [
        'mail' => [
            'enabled' => true,
            'from' => 'notifications@example.com',
        ],
        'slack' => [
            'enabled' => false,
            'webhook' => env('SLACK_WEBHOOK'),
        ],
    ],
    
  3. First Use Case: Notifying on User Registration Dispatch an event in your UserController:

    use B2PWeb\BDFEventNotifier\Facades\EventNotifier;
    use App\Events\UserRegistered;
    
    public function register(Request $request)
    {
        $user = User::create($request->validated());
        EventNotifier::notify(new UserRegistered($user));
    }
    

    Define a listener for the event (e.g., app/Listeners/NotifyUserRegistered.php):

    public function handle(UserRegistered $event)
    {
        EventNotifier::send('mail', new UserRegisteredMail($event->user));
    }
    

    Register the listener in EventServiceProvider:

    protected $listen = [
        UserRegistered::class => [
            NotifyUserRegistered::class,
        ],
    ];
    

Implementation Patterns

Channel-Agnostic Workflows

  1. Decoupled Notifications Use the package’s EventNotifier facade to send notifications without coupling to specific channels:

    EventNotifier::send('mail', new InvoicePaidMail($invoice));
    EventNotifier::send('slack', new SlackAlert($invoice));
    
  2. Dynamic Channel Routing Route notifications dynamically based on user preferences or event metadata:

    $channels = $user->preferredNotificationChannels; // e.g., ['mail', 'slack']
    foreach ($channels as $channel) {
        EventNotifier::send($channel, new GenericAlert($event));
    }
    
  3. Batch Processing Process events in bulk (e.g., for analytics or reporting):

    $events = Event::where('processed', false)->limit(100)->get();
    foreach ($events as $event) {
        EventNotifier::notify($event);
    }
    Event::whereIn('id', $events->pluck('id'))->update(['processed' => true]);
    

Integration Tips

  • Laravel Events Extend existing Laravel events or create custom ones. Example:

    class OrderShipped implements ShouldQueue
    {
        public function __construct(public Order $order) {}
    }
    
  • Queue Integration Leverage Laravel queues for async processing. Ensure your events implement ShouldQueue:

    EventNotifier::notify(new OrderShipped($order))->onQueue('notifications');
    
  • Testing Mock the EventNotifier facade in tests:

    $this->mock(EventNotifier::class)->shouldReceive('send')->once();
    

Gotchas and Tips

Pitfalls

  1. Channel Configuration

    • Issue: Forgetting to enable channels in config/bdf-event-notifier.php will silently fail.
    • Fix: Validate config during bootstrapping or use a trait to enforce channel checks:
      if (!config('bdf-event-notifier.channels.mail.enabled')) {
          throw new \RuntimeException('Mail channel is disabled.');
      }
      
  2. Event Serialization

    • Issue: Complex event payloads (e.g., Eloquent models with relationships) may fail to serialize for queued jobs.
    • Fix: Use ->onQueue() with serialize: false or implement __serialize() in your event:
      public function __serialize()
      {
          return ['user_id' => $this->user->id];
      }
      
  3. Duplicate Notifications

    • Issue: Events may be reprocessed if queues fail or listeners retry.
    • Fix: Add a processed_at timestamp to your events table and deduplicate:
      if ($event->processed_at) return;
      $event->update(['processed_at' => now()]);
      

Debugging

  • Log Notifications Enable logging in the config:

    'log' => [
        'enabled' => true,
        'channel' => 'single',
    ],
    

    Check storage/logs/laravel.log for failed notifications.

  • Channel-Specific Errors Wrap channel logic in try-catch blocks to log errors per channel:

    try {
        EventNotifier::send('slack', $alert);
    } catch (\Exception $e) {
        \Log::error("Slack notification failed: " . $e->getMessage());
    }
    

Extension Points

  1. Custom Channels Create a new channel driver by implementing B2PWeb\BDFEventNotifier\Contracts\Channel:

    class TeamsChannel implements Channel
    {
        public function send($event)
        {
            // Custom logic for Microsoft Teams
        }
    }
    

    Register it in the config:

    'channels' => [
        'teams' => [
            'enabled' => true,
            'webhook' => env('TEAMS_WEBHOOK'),
        ],
    ],
    
  2. Event Transformers Use transformers to modify payloads before sending:

    EventNotifier::send('mail', new UserRegisteredMail($user))
        ->transform(fn ($payload) => [
            'subject' => "Welcome, {$payload['user']['name']}!",
            // ...
        ]);
    
  3. Middleware Add middleware to events (e.g., for rate limiting or auth):

    EventNotifier::notify($event)->through([ThrottleNotifications::class]);
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle