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

Notifier Server Bundle Laravel Package

coka/notifier-server-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require coka/notifier-server-bundle
    

    Register the bundle in config/bundles.php:

    CedrickOka\NotifierServerBundle\CedrickOkaNotifierServerBundle::class => ['all' => true],
    
  2. Publish Configuration

    php artisan vendor:publish --provider="CedrickOka\NotifierServerBundle\CedrickOkaNotifierServerBundle" --tag="config"
    

    This generates config/notifier_server.php. Configure your notification channels (e.g., email, sms, slack) under channels.

  3. First Use Case: Sending a Notification Inject the NotifierServer service into a controller or command:

    use CedrickOka\NotifierServerBundle\NotifierServer;
    
    class ExampleController extends Controller
    {
        public function __construct(private NotifierServer $notifier)
        {
        }
    
        public function sendNotification()
        {
            $this->notifier->send(
                to: 'user@example.com', // Recipient (format depends on channel)
                channel: 'email',       // Channel name from config
                data: [
                    'subject' => 'Hello!',
                    'message' => 'This is a test notification.',
                ]
            );
        }
    }
    
  4. Verify Configuration Check config/notifier_server.php for channel-specific settings (e.g., API keys, endpoints). Example for Slack:

    'channels' => [
        'slack' => [
            'webhook_url' => env('SLACK_WEBHOOK_URL'),
            'default_icon' => ':robot_face:',
        ],
    ],
    

Implementation Patterns

Core Workflow: Sending Notifications

  1. Define Channels Extend the bundle by adding custom channels in config/notifier_server.php:

    'channels' => [
        'custom_webhook' => [
            'url' => env('CUSTOM_WEBHOOK_URL'),
            'method' => 'POST',
        ],
    ],
    
  2. Dynamic Recipients Use arrays for multi-recipient notifications:

    $this->notifier->send(
        to: ['user1@example.com', 'user2@example.com'],
        channel: 'email',
        data: ['subject' => 'Group Alert']
    );
    
  3. Async Processing Queue notifications for background processing:

    $this->notifier->queue(
        to: 'user@example.com',
        channel: 'sms',
        data: ['message' => 'Your OTP is 1234']
    );
    

    Ensure the notifier:send queue listener is set up (check app/Console/Kernel.php).

  4. Event Listeners Attach listeners to notifications for logging or analytics:

    // In a service provider
    $this->app->make('notifier')->extend('email', function ($app) {
        return new class($app['notifier.transport.email']) {
            public function send($to, $data)
            {
                // Pre-send logic (e.g., log)
                $result = $this->transport->send($to, $data);
                // Post-send logic
                return $result;
            }
        };
    });
    
  5. Templates Use Twig or Blade templates for dynamic content:

    $this->notifier->send(
        to: 'user@example.com',
        channel: 'email',
        data: [
            'template' => 'emails.welcome', // Path to Twig/Blade template
            'variables' => ['name' => 'John'],
        ]
    );
    

Integration Tips

  • Laravel Notifications Bridge If using Laravel’s built-in Notification system, create a custom channel:

    // app/Providers/NotifierServiceProvider.php
    public function register()
    {
        $this->app->bind('notifier.channel.email', function ($app) {
            return new class($app['mailer']) {
                public function send($to, $data)
                {
                    return $this->mailer->send(new \App\Notifications\CustomNotification($data), $to);
                }
            };
        });
    }
    
  • Testing Mock the NotifierServer in tests:

    $notifier = Mockery::mock(NotifierServer::class);
    $notifier->shouldReceive('send')->once();
    $this->app->instance(NotifierServer::class, $notifier);
    
  • Rate Limiting Implement rate limiting per channel using middleware:

    // config/notifier_server.php
    'middleware' => [
        'email' => \CedrickOka\NotifierServerBundle\Middleware\RateLimit::class,
    ],
    

Gotchas and Tips

Pitfalls

  1. Channel Configuration Mismatch

    • Issue: Notifications fail silently if channel in send() doesn’t match config/notifier_server.php.
    • Fix: Validate channel names case-sensitively or normalize them in the bundle’s NotifierServer class.
  2. Missing Queue Setup

    • Issue: Queued notifications won’t process if the notifier:send queue listener is missing.
    • Fix: Add to app/Console/Kernel.php:
      protected function schedule(Schedule $schedule)
      {
          $schedule->job(new \CedrickOka\NotifierServerBundle\Jobs\SendNotification)->everyMinute();
      }
      
  3. Data Serialization

    • Issue: Complex data (e.g., objects) may not serialize correctly for API channels (e.g., Slack).
    • Fix: Flatten data or use json_encode() explicitly:
      $this->notifier->send(
          to: env('SLACK_WEBHOOK_URL'),
          channel: 'slack',
          data: ['text' => json_encode(['blocks' => [...]])]
      );
      
  4. Environment Variables

    • Issue: Hardcoded API keys in config instead of .env.
    • Fix: Use env() in config/notifier_server.php:
      'channels' => [
          'slack' => [
              'webhook_url' => env('SLACK_WEBHOOK_URL', 'default_url'),
          ],
      ],
      
  5. Error Handling

    • Issue: Exceptions from channels (e.g., API timeouts) may not bubble up.
    • Fix: Wrap channel calls in try-catch and log errors:
      // In NotifierServer.php
      try {
          $response = $this->getTransport($channel)->send($to, $data);
      } catch (\Exception $e) {
          Log::error("Notification failed for {$channel}: " . $e->getMessage());
          throw new \RuntimeException("Notification failed", 0, $e);
      }
      

Debugging Tips

  1. Enable Debug Mode Set debug: true in config/notifier_server.php to log raw payloads:

    'debug' => env('NOTIFIER_DEBUG', false),
    
  2. Check Queue Jobs Monitor queued notifications:

    php artisan queue:work --queue=notifier
    
  3. Inspect Payloads Log the final payload before sending:

    // In NotifierServer.php
    if ($this->config['debug']) {
        Log::debug('Notification payload', [
            'channel' => $channel,
            'to' => $to,
            'data' => $data,
        ]);
    }
    

Extension Points

  1. Custom Transports Extend the TransportInterface to add new channels:

    namespace App\Notifier;
    
    use CedrickOka\NotifierServerBundle\Transport\TransportInterface;
    
    class CustomTransport implements TransportInterface
    {
        public function send($to, $data)
        {
            // Custom logic (e.g., HTTP request to a custom API)
            return ['success' => true];
        }
    }
    

    Register it in config/notifier_server.php:

    'transports' => [
        'custom' => App\Notifier\CustomTransport::class,
    ],
    
  2. Override Default Behavior Replace the NotifierServer class entirely by binding it in a service provider:

    $this->app->bind(NotifierServer::class, function ($app) {
        return new \App\Services\CustomNotifierServer(
            $app['notifier.config'],
            $app['notifier.transport.factory']
        );
    });
    
  3. Add Validation Validate notification data before sending:

    // In NotifierServer.php
    public function send($to, $channel, $data)
    {
        if (!$this->validateData($channel, $data)) {
            throw new \InvalidArgumentException("Invalid data for {$channel}");
        }
        // ... rest of the logic
    }
    
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