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

Dabsquared Push Notifications Bundle Laravel Package

dabsquared/dabsquared-push-notifications-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require dabsquared/dabsquared-push-notifications-bundle

Enable the bundle in config/bundles.php:

Dabsquared\PushNotificationsBundle\DabsquaredPushNotificationsBundle::class => ['all' => true],
  1. Configuration: Update config/packages/dabsquared_push_notifications.yaml with your API keys (GCM, APNS, etc.) and database settings.

  2. First Use Case: Register a device via the admin interface (accessible at /admin/push_notifications/devices). Use the provided UI to:

    • Add a new device (e.g., iOS/Android token).
    • Assign the device to a user (via user_id field).
    • Send a test notification to verify setup.
  3. Sending a Notification: Use the admin panel (/admin/push_notifications/messages) to create a new message:

    • Select target devices/users.
    • Define payload (title, message, custom data).
    • Click "Send" to dispatch via the configured providers (GCM/APNS).

Implementation Patterns

Core Workflows

  1. Device Registration:

    • Frontend: Capture device tokens (e.g., from FCM or APNS) via JavaScript (e.g., Firebase SDK or PushNotification plugin).
    • Backend: POST to /api/push_notifications/devices with:
      {
        "token": "device_token_here",
        "user_id": 123,
        "platform": "ios" // or "android", "blackberry", "safari"
      }
      
    • Validation: Ensure tokens are unique and platform-specific.
  2. Sending Notifications:

    • Admin UI: Use the built-in dashboard to craft and send messages.
    • Programmatic API:
      use Dabsquared\PushNotificationsBundle\Manager\PushNotificationManager;
      
      $manager = $this->get('dabsquared_push_notifications.manager');
      $message = $manager->createMessage();
      $message->setTitle('Hello!');
      $message->setMessage('Check this out!');
      $message->addDevice($deviceEntity); // or addUser($userEntity)
      $manager->send($message);
      
    • Bulk Sending: Target users/devices via:
      $message->addUser($user); // Sends to all devices linked to the user
      $message->addDevice($device); // Sends to a specific device
      
  3. Payload Customization:

    • Extend the Message entity to include custom data:
      $message->setData(['key' => 'value']); // Passed to the device as-is
      
    • For Android (GCM), use:
      $message->setAndroidData(['sound' => 'default', 'priority' => 'high']);
      
    • For iOS (APNS), use:
      $message->setIosData(['badge' => 1, 'sound' => 'default']);
      
  4. Event Listeners:

    • Hook into notification lifecycle via Symfony events:
      # config/services.yaml
      Dabsquared\PushNotificationsBundle\EventListener\PushNotificationListener:
        tags:
          - { name: kernel.event_listener, event: dabsquared.push_notifications.send, method: onSend }
      
    • Example listener:
      public function onSend(PushNotificationEvent $event) {
          $message = $event->getMessage();
          // Log, analyze, or modify the message before sending
      }
      
  5. Scheduled Notifications:

    • Use Symfony’s CronBundle or Laravel Tasks to queue delayed messages:
      $message->setScheduledAt(new \DateTime('+1 hour'));
      $manager->send($message);
      

Gotchas and Tips

Pitfalls

  1. Deprecated Dependencies:

    • The bundle relies on GCM (now Firebase Cloud Messaging) and C2DM (shut down in 2012). Replace GCM references with FCM in your code:
      // Old (GCM):
      $message->setGcmApiKey('your_key');
      // New (FCM):
      $message->setFcmApiKey('your_fcm_key');
      
    • For iOS, ensure you’re using APNs (not MPNS) and have valid .pem certificates.
  2. Database Schema:

    • The bundle assumes a device table with columns: id, token, user_id, platform, created_at. Customize migrations if needed:
      // Example migration for custom fields
      Schema::table('device', function (Blueprint $table) {
          $table->string('app_version')->nullable();
          $table->boolean('is_active')->default(true);
      });
      
  3. Token Expiry:

    • Device tokens (especially APNS) expire. Implement a token refresh workflow:
      • Frontend: Detect token changes and POST new tokens to /api/push_notifications/devices/{id}.
      • Backend: Invalidate old tokens via a PushNotificationEvent listener.
  4. Rate Limits:

    • APNS/FCM have strict rate limits. Implement exponential backoff in your PushNotificationManager:
      try {
          $manager->send($message);
      } catch (RateLimitExceededException $e) {
          sleep(2 ** $attempt); // Exponential backoff
          $manager->send($message);
      }
      
  5. Admin Panel Quirks:

    • The admin UI is basic. Extend it with EasyAdmin or SonataAdmin for better UX:
      # config/packages/easy_admin.yaml
      easy_admin:
          entities:
              Dabsquared\PushNotificationsBundle\Entity\Device:
                  class: Device
                  list: [id, token, platform, user]
                  form: [token, platform, user, is_active]
      

Debugging

  1. Logging:

    • Enable debug mode in config/packages/dabsquared_push_notifications.yaml:
      debug: true
      
    • Check logs at var/log/dev.log for failed sends.
  2. Payload Validation:

  3. Common Errors:

    • APNS: "Invalid Token" → Regenerate certificates in Apple Developer Portal.
    • FCM: "InvalidRegistration" → Token expired; request a new one from the device.
    • Database: "Column not found" → Run migrations or adjust schema.

Extension Points

  1. Custom Providers:

    • Extend Dabsquared\PushNotificationsBundle\Provider\AbstractProvider to support new platforms (e.g., Web Push):
      class WebPushProvider extends AbstractProvider {
          public function send($message, $device) {
              // Implement Web Push logic
          }
      }
      
    • Register the provider in services.yaml:
      Dabsquared\PushNotificationsBundle\Provider\WebPushProvider:
          tags:
              - { name: dabsquared.push_notifications.provider, platform: 'web' }
      
  2. Message Transformers:

    • Override payload formatting for specific platforms:
      $manager->addTransformer('ios', function ($message, $device) {
          $message->setData(array_merge($message->getData(), ['category' => 'news']));
      });
      
  3. Webhooks:

    • Integrate with third-party services (e.g., Slack, Twilio) via post-send events:
      $event->getMessage()->getData()['webhook_url'] = 'https://your-service.com/webhook';
      
  4. Analytics:

    • Track delivery status by extending the Device entity:
      // Add to Device entity
      /**
       * @ORM\Column(type="boolean", nullable=true)
       */
      private $lastDeliveryStatus;
      
      // Update via listener
      public function onSend(PushNotificationEvent $event) {
          $device = $event->getDevice();
          $device->setLastDeliveryStatus($event->getStatus());
          $em->persist($device);
      }
      

Performance Tips

  1. Batch Processing:

    • Use Symfony’s Messenger component to queue notifications:
      $messageBus->dispatch(new SendPushNotification($message));
      
    • Process in bulk via a worker:
      $manager->sendBatch($messages); // Hypothetical batch method
      
  2. Caching:

    • Cache user-device mappings to reduce DB queries:
      $cache->set("user_{$userId}_devices", $devices, 3600);
      
  3. Async Sending:

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