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

Push Notifications Bundle Laravel Package

bluetea/push-notifications-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer (note: package is archived, use with caution):

    composer require bluetea/push-notifications-bundle dev-master
    

    Register in AppKernel.php:

    new Bluetea\PushNotificationsBundle\BlueteaPushNotificationsBundle(),
    
  2. Basic Configuration Define endpoints in config.yml:

    bluetea_push_notifications:
        endpoints:
            - { name: "firebase", url: "https://fcm.googleapis.com/fcm/send", auth_key: "%env(FIREBASE_KEY)%" }
    
  3. First Use Case Inject the PushNotificationService and send a notification:

    use Bluetea\PushNotificationsBundle\Service\PushNotificationService;
    
    class NotificationController extends Controller
    {
        public function sendNotification(PushNotificationService $pushService)
        {
            $notification = [
                'to' => '/topics/news',
                'notification' => [
                    'title' => 'Hello',
                    'body' => 'World!'
                ]
            ];
            $pushService->send('firebase', $notification);
        }
    }
    

Implementation Patterns

Dependency Injection & Services

  • Tagged Services: The bundle registers endpoints as tagged services. Extend by creating custom services tagged bluetea.push_notification.endpoint.
  • Service Integration:
    # services.yml
    services:
        App\Service\CustomEndpoint:
            tags:
                - { name: bluetea.push_notification.endpoint, alias: "custom_endpoint" }
    

Workflows

  1. Dynamic Endpoint Routing Use the PushNotificationService to route notifications to configured endpoints:

    $pushService->send('firebase', $payload);
    
  2. Batch Processing Queue notifications for async delivery (e.g., with Symfony Messenger):

    $pushService->queue('firebase', $payload);
    
  3. Template-Based Notifications Combine with Twig to generate dynamic payloads:

    {# templates/notification.html.twig #}
    {
        "to": "{{ token }}",
        "notification": {
            "title": "{{ title }}",
            "body": "{{ body|raw }}"
        }
    }
    
    $payload = $this->twig->render('notification.html.twig', $context);
    $pushService->send('firebase', json_decode($payload, true));
    

Integration Tips

  • Environment Variables: Store API keys in .env (e.g., FIREBASE_KEY).
  • Logging: Enable debug mode to log failed requests:
    bluetea_push_notifications:
        debug: true
    
  • Error Handling: Wrap calls in try-catch to handle HTTP errors gracefully:
    try {
        $pushService->send('firebase', $notification);
    } catch (\Exception $e) {
        $this->addFlash('error', 'Notification failed: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Archived Package

    • No active maintenance; fork or migrate to alternatives like symfony/messenger + firebase/php-jwt.
    • Example migration:
      composer require firebase/php-jwt symfony/messenger
      
  2. Configuration Overrides

    • Endpoint URLs/auth keys are not validated on config load. Always test connections post-deployment.
  3. Payload Validation

    • The underlying library may reject malformed payloads silently. Validate JSON before sending:
      if (!json_validate($payload)) {
          throw new \InvalidArgumentException('Invalid JSON payload');
      }
      

Debugging

  • HTTP Errors: Check Symfony’s profiler for failed requests or enable debug: true in config.
  • Endpoint-Specific Issues:
    • Firebase: Ensure auth_key is a valid Server Key (not Client Key).
    • Custom endpoints: Verify CORS headers and SSL certificates.

Extension Points

  1. Custom Endpoints Extend the Bluetea\PushNotificationsBundle\Endpoint\AbstractEndpoint class:

    class CustomEndpoint extends AbstractEndpoint
    {
        protected function sendRequest($url, $data)
        {
            // Custom logic (e.g., retry logic, headers)
            return $this->httpClient->post($url, [
                'headers' => ['X-Custom-Header' => 'value'],
                'body' => json_encode($data)
            ]);
        }
    }
    
  2. Event Listeners Subscribe to bluetea.push_notification.send events to modify payloads:

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Bluetea\PushNotificationsBundle\Event\PushNotificationEvent;
    
    class NotificationSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'bluetea.push_notification.send' => 'onSendNotification'
            ];
        }
    
        public function onSendNotification(PushNotificationEvent $event)
        {
            $event->setPayload(array_merge($event->getPayload(), ['priority' => 'high']));
        }
    }
    
  3. Response Handling Override the onResponse method in custom endpoints to parse provider-specific responses (e.g., Firebase’s sendResponse):

    protected function onResponse(\Psr\Http\Message\ResponseInterface $response)
    {
        $data = json_decode($response->getBody(), true);
        if (isset($data['failure'])) {
            throw new \RuntimeException('Failed to send: ' . $data['failure']);
        }
    }
    

Performance Tips

  • Batch Endpoints: For high-volume apps, implement batching in custom endpoints:
    $batch = ['registration_ids' => [$token1, $token2], 'data' => $payload];
    $this->sendRequest($url, $batch);
    
  • Caching: Cache API keys/tokens if endpoints support it (e.g., Firebase’s access_token).

```markdown
## Migration Note
For new projects, consider:
- **Symfony Messenger** + **Firebase Admin SDK** for decoupled, scalable notifications.
- **Laravel Echo/Pusher** for real-time web push notifications.
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky