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

Ionic Pusher Bundle Laravel Package

draw/ionic-pusher-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add the package via Composer:

    composer require draw/ionic-pusher-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Draw\IonicPusherBundle\IonicPusherBundle::class => ['all' => true],
    ];
    
  2. Configure the Bundle Publish the default configuration:

    php bin/console config:dump-reference | grep ionic_pusher
    

    Or manually configure in config/packages/ionic_pusher.yaml:

    ionic_pusher:
        app_id: 'YOUR_IONIC_APP_ID'
        api_key: 'YOUR_IONIC_API_KEY'
        secret: 'YOUR_IONIC_SECRET'
        environment: 'production' # or 'development'
    
  3. First Use Case: Send a Push Notification Inject the IonicPusher service and trigger a push:

    use Draw\IonicPusherBundle\Service\IonicPusher;
    
    class MyController extends AbstractController
    {
        public function __invoke(IonicPusher $pusher)
        {
            $pusher->sendPush(
                'YOUR_DEVICE_TOKEN',
                'Hello from Laravel!',
                ['custom' => 'data']
            );
            return new Response('Push sent!');
        }
    }
    

Implementation Patterns

Core Workflows

  1. Sending Push Notifications

    • Basic Push: Use sendPush() with a device token, message, and optional payload:
      $pusher->sendPush($deviceToken, 'Message', ['key' => 'value']);
      
    • Batch Pushes: Loop through device tokens (e.g., from a database):
      foreach ($deviceTokens as $token) {
          $pusher->sendPush($token, 'Update', ['urgent' => true]);
      }
      
  2. Event-Driven Pushes

    • Trigger pushes from Symfony events (e.g., KernelEvents::TERMINATE):
      use Symfony\Component\HttpKernel\Event\TerminateEvent;
      use Symfony\Component\HttpKernel\KernelEvents;
      
      $eventDispatcher->addListener(KernelEvents::TERMINATE, function (TerminateEvent $event) {
          if ($event->getRequest()->isXmlHttpRequest()) {
              $pusher->sendPush('token', 'New data available!');
          }
      });
      
  3. Integration with Ionic Framework

    • Use Ionic’s Push service in your frontend to handle incoming pushes:
      import { Push } from '@ionic-native/push/ngx';
      
      constructor(private push: Push) {
          this.push.initialize().then(() => {
              this.push.on('notification').subscribe(data => {
                  console.log('Push received:', data);
              });
          });
      }
      

Advanced Patterns

  1. Dynamic Device Token Storage Store tokens in the database (e.g., users table) and fetch them when needed:

    $tokens = User::whereNotNull('device_token')->pluck('device_token');
    $pusher->sendPush($tokens, 'Broadcast message');
    
  2. Conditional Pushes Use Symfony’s expression language to filter recipients:

    $tokens = $userRepository->getTokensForCondition('active');
    $pusher->sendPush($tokens, 'Conditional message');
    
  3. Error Handling Wrap push calls in try-catch blocks to log failures:

    try {
        $pusher->sendPush($token, 'Message');
    } catch (\Exception $e) {
        $this->logger->error('Push failed: ' . $e->getMessage());
    }
    

Gotchas and Tips

Common Pitfalls

  1. Environment Mismatches

    • Ensure ionic_pusher.environment matches your Ionic dashboard settings (e.g., development vs. production).
    • Fix: Double-check the config after deployment.
  2. Device Token Validity

    • Ionic may invalidate tokens after app updates or reinstalls.
    • Fix: Implement a token refresh mechanism in your Ionic app and update the backend.
  3. Rate Limiting

    • Ionic’s API has rate limits (e.g., 1 push/sec in development).
    • Fix: Throttle pushes using Symfony’s RateLimiter or queue them with Symfony Messenger.
  4. Missing Dependencies

    • The bundle assumes guzzlehttp/guzzle is installed (it’s a dependency, but verify).
    • Fix: Run composer require guzzlehttp/guzzle if missing.

Debugging Tips

  1. Enable Verbose Logging Add to config/packages/monolog.yaml:

    handlers:
        ionic_pusher:
            type: stream
            path: "%kernel.logs_dir%/ionic_pusher.log"
            level: debug
    
  2. Test with Postman Manually test the Ionic API endpoint to isolate issues:

    POST https://push.ionic.io/api/v1/push
    Headers: {
        "X-Ionic-Application-Id": "YOUR_APP_ID",
        "Authorization": "Basic YOUR_API_KEY"
    }
    Body: { "tokens": ["TOKEN"], "message": { "text": "Test" } }
    
  3. Check Ionic Dashboard

    • Verify your app is active in the Ionic Dashboard.
    • Ensure the API key/secret are correct and not revoked.

Extension Points

  1. Custom Payload Transformers Override the default payload structure by extending the IonicPusher service:

    use Draw\IonicPusherBundle\Service\IonicPusher;
    
    class CustomIonicPusher extends IonicPusher
    {
        protected function transformPayload(array $payload): array
        {
            $payload['custom_key'] = 'custom_value';
            return parent::transformPayload($payload);
        }
    }
    

    Register the service in config/services.yaml:

    services:
        Draw\IonicPusherBundle\Service\IonicPusher:
            class: App\Service\CustomIonicPusher
    
  2. Queue Pushes for Async Processing Use Symfony Messenger to avoid timeouts:

    use Symfony\Component\Messenger\MessageBusInterface;
    
    $bus->dispatch(new SendPushMessage($token, 'Message', $payload));
    

    Define the message and handler:

    class SendPushMessage
    {
        public function __construct(
            private string $token,
            private string $message,
            private array $payload
        ) {}
    }
    
    class SendPushHandler
    {
        public function __invoke(SendPushMessage $message, IonicPusher $pusher)
        {
            $pusher->sendPush($message->token, $message->message, $message->payload);
        }
    }
    
  3. Webhook Integration Listen for Ionic push events (e.g., delivery reports) via webhooks:

    use Symfony\Component\HttpFoundation\Request;
    
    public function handleIonicWebhook(Request $request)
    {
        $data = json_decode($request->getContent(), true);
        // Process event (e.g., log delivery status)
    }
    

    Configure the webhook URL in the Ionic dashboard.

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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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