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

Pushe Notification Bundle Laravel Package

borsaco/pushe-notification-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require borsaco/pushe-notification-bundle in your Symfony project root. Ensure your composer.json includes the package under require.

  2. Bundle Registration Add the bundle to AppKernel.php:

    public function registerBundles()
    {
        $bundles = [
            // ...
            new Borsaco\PusheNotificationBundle\PusheNotificationBundle(),
        ];
    }
    
  3. Configuration Add your Pushe.co API token to config/packages/pushe_notification.yaml:

    pushe_notification:
        token: "%env(PUSHE_TOKEN)%"  # Recommended: Use env vars for security
    

    (Optional) Enable environment variables in .env:

    PUSHE_TOKEN=your_token_here
    
  4. First Notification Inject the service into a controller or command:

    use Borsaco\PusheNotificationBundle\Service\PusheNotification;
    
    class MyController extends AbstractController
    {
        public function __construct(private PusheNotification $pushe)
        {}
    
        public function sendNotification()
        {
            $this->pushe->send([
                'message' => 'Hello from Symfony!',
                'targets' => ['device_token_1', 'device_token_2'],
            ]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Sending Notifications Use the send() method with an associative array:

    $this->pushe->send([
        'message' => 'Your order is confirmed!',
        'title'   => 'Order Update',
        'targets' => ['token1', 'token2'], // Array of device tokens
        'data'    => ['key' => 'value'],    // Optional custom payload
    ]);
    
    • Targets: Required. Array of device tokens (strings).
    • Message/Title: Required. Localized strings (Pushe handles translation).
    • Data: Optional. Key-value pairs for deep linking or custom logic.
  2. Batch Processing For large lists of devices, chunk targets to avoid API rate limits:

    $batchSize = 100;
    $devices = DeviceToken::all()->pluck('token');
    
    foreach (array_chunk($devices, $batchSize) as $chunk) {
        $this->pushe->send(['message' => 'Batch update', 'targets' => $chunk]);
    }
    
  3. Event-Driven Notifications Trigger notifications from Symfony events (e.g., KernelEvents::TERMINATE):

    // src/EventListener/NotificationListener.php
    class NotificationListener implements EventSubscriber
    {
        public function onKernelTerminate(GetResponseEvent $event)
        {
            if ($event->getRequest()->isXmlHttpRequest()) {
                $this->pushe->send(['message' => 'Request processed', 'targets' => [...]]);
            }
        }
    }
    
  4. Dependency Injection Prefer constructor injection over container access:

    // Correct (recommended)
    public function __construct(private PusheNotification $pushe) {}
    
    // Avoid (legacy)
    $this->container->get('pushe_notification');
    

Integration Tips

  1. Symfony Messenger Decouple notifications by dispatching messages:

    // src/Message/SendPusheNotification.php
    class SendPusheNotification implements MessageInterface
    {
        public string $message;
        public array $targets;
    }
    
    // Worker
    $bus->dispatch(new SendPusheNotification('Hello', ['token1']));
    
  2. Doctrine Events Send notifications on entity lifecycle events:

    // src/EventSubscriber/OrderSubscriber.php
    class OrderSubscriber implements EventSubscriber
    {
        public function postPersist(Order $order)
        {
            $this->pushe->send([
                'message' => 'New order #'.$order->id,
                'targets' => $order->user->deviceTokens,
            ]);
        }
    }
    
  3. Translation Support Use Symfony’s translation system for localized messages:

    $this->pushe->send([
        'message' => $this->translator->trans('notification.order.confirmed'),
        'targets' => [...],
    ]);
    
  4. Logging Wrap calls in a try-catch to log failures:

    try {
        $this->pushe->send([...]);
    } catch (\Exception $e) {
        $this->logger->error('Pushe notification failed', ['error' => $e->getMessage()]);
    }
    

Gotchas and Tips

Pitfalls

  1. Token Security

    • Never hardcode tokens in config files. Use .env or Symfony’s parameter_bag.
    • Validate tokens: Pushe may silently fail with invalid tokens. Log responses to debug:
      $response = $this->pushe->send([...]);
      $this->logger->debug('Pushe response', ['status' => $response->getStatusCode()]);
      
  2. Rate Limits

    • Pushe’s free tier has strict limits (~1000 messages/day). Monitor usage via their dashboard.
    • Workaround: Implement exponential backoff for retries:
      $attempts = 0;
      while ($attempts < 3) {
          try {
              $this->pushe->send([...]);
              break;
          } catch (RateLimitException $e) {
              sleep(2 ** $attempts); // Exponential delay
              $attempts++;
          }
      }
      
  3. Device Token Management

    • Invalid tokens: Pushe will fail silently. Clean up stale tokens periodically:
      // Pseudocode: Validate tokens via Pushe API
      $validTokens = array_filter($deviceTokens, fn($token) => $this->pushe->validateToken($token));
      
  4. Payload Size Limits

    • Pushe truncates messages > 4096 bytes. Test with long messages:
      $longMessage = str_repeat('a', 5000);
      $this->pushe->send(['message' => $longMessage]); // May be truncated
      

Debugging

  1. Enable API Debugging Add a debug endpoint to log raw API calls:

    // src/Controller/PusheDebugController.php
    class PusheDebugController extends AbstractController
    {
        public function debug(PusheNotification $pushe)
        {
            $pushe->setDebug(true); // Enable debug mode
            $pushe->send(['message' => 'Debug test', 'targets' => [...]]);
            return $this->json($pushe->getLastResponse());
        }
    }
    
  2. Common Errors

    Error Cause Solution
    Invalid token Wrong API token Check .env and Pushe dashboard
    No targets provided Empty targets array Validate input data
    HTTP 429 Too Many Requests Rate limit exceeded Implement retries/backoff
    HTTP 500 Internal Server Error Pushe API issue Check Pushe status page

Extension Points

  1. Custom Response Handling Extend the service to parse Pushe’s response:

    // src/Service/ExtendedPusheNotification.php
    class ExtendedPusheNotification extends PusheNotification
    {
        public function send(array $data): array
        {
            $response = parent::send($data);
            return json_decode($response->getBody(), true);
        }
    }
    
  2. Webhook Integration Use Pushe’s webhook feature to trigger Symfony events:

    // src/EventListener/PusheWebhookListener.php
    class PusheWebhookListener
    {
        public function onPusheWebhook(Request $request)
        {
            $data = json_decode($request->getContent(), true);
            if ($data['event'] === 'delivery_receipt') {
                $this->handleDelivery($data['device_token']);
            }
        }
    }
    
  3. Testing Mock the service in PHPUnit:

    $mock = $this->createMock(PusheNotification::class);
    $mock->method('send')->willReturn(new Response('{"success":true}'));
    
    $controller = new MyController($mock);
    $controller->sendNotification();
    
  4. Configuration Overrides Dynamically override the token per environment:

    # config/packages/dev/pushe_notification.yaml
    pushe_notification:
        token: "%env(PUSHE_TOKEN_DEV)%"
    
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