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 Php Laravel Package

authbucket/push-php

PHP library for sending push notifications to mobile devices. Includes a Silex AuthBucketPushServiceProvider for demos/tests, with configurable models and model managers. Install via Composer (authbucket/push-php) and extend for Symfony2/Drupal wrappers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require authbucket/push-php
    

    For Laravel, ensure compatibility by checking the Symfony components version (Laravel 5.5+ uses Symfony 4.x, while this package may rely on older versions).

  2. Basic Setup Register the AuthBucketPushServiceProvider in your Silex app (if using Silex) or integrate the core AuthBucket\Push components directly. For Laravel, manually instantiate the required services:

    use AuthBucket\Push\Push;
    use AuthBucket\Push\Provider\AuthBucketPushServiceProvider;
    
    $push = new Push();
    
  3. First Use Case Send a push notification to a device token:

    $push = new Push();
    $push->setProvider('apns'); // or 'gcm' for Android
    $push->setToken('device_token_here');
    $push->setMessage('Hello from Laravel!');
    $push->send();
    

Where to Look First

  • Core Classes: Focus on AuthBucket\Push\Push for sending notifications.
  • Providers: Review AuthBucket\Push\Provider\ApnsProvider and AuthBucket\Push\Provider\GcmProvider for platform-specific logic.
  • Demo: Clone the demo repo for a working example.

Implementation Patterns

Usage Patterns

  1. Platform-Specific Providers Use ApnsProvider for iOS and GcmProvider for Android:

    $push = new Push();
    $push->setProvider('apns')
         ->setCertificatePath('/path/to/cert.pem')
         ->setToken('ios_device_token')
         ->setMessage('iOS Notification')
         ->send();
    
  2. Batch Sending Send notifications to multiple devices:

    $push->setProvider('gcm')
         ->setTokens(['token1', 'token2', 'token3'])
         ->setMessage('Batch Notification')
         ->send();
    
  3. Custom Payloads Extend payloads with additional data (e.g., deep links, custom keys):

    $push->setPayload([
        'alert' => 'Custom Alert',
        'badge' => 1,
        'sound' => 'default',
        'custom_key' => 'custom_value'
    ]);
    
  4. Error Handling Wrap sending in a try-catch block to handle failures:

    try {
        $push->send();
    } catch (\Exception $e) {
        Log::error('Push failed: ' . $e->getMessage());
    }
    

Workflows

  1. Token Management Store device tokens in a database (e.g., users_devices table) and fetch them when sending notifications:

    $tokens = DB::table('users_devices')->where('user_id', $userId)->pluck('device_token');
    $push->setTokens($tokens->toArray());
    
  2. Event-Based Triggers Dispatch notifications via Laravel events (e.g., OrderShipped):

    event(new OrderShipped($order));
    // In listener:
    $tokens = $order->user->devices->pluck('device_token');
    $push->setTokens($tokens)->setMessage('Your order is shipped!')->send();
    
  3. Queueing Notifications Use Laravel queues to avoid timeouts for large batches:

    dispatch(new SendPushNotification($tokens, 'Hello!'))->onQueue('push');
    

Integration Tips

  • Laravel Service Provider Bind the Push class in AppServiceProvider:

    $this->app->singleton('push', function () {
        return new \AuthBucket\Push\Push();
    });
    
  • Configuration Store provider-specific settings (e.g., API keys, certificate paths) in config/push.php:

    'providers' => [
        'apns' => [
            'certificate_path' => env('APNS_CERT_PATH'),
            'passphrase' => env('APNS_PASSPHRASE'),
        ],
        'gcm' => [
            'api_key' => env('GCM_API_KEY'),
        ],
    ];
    
  • Middleware for Auth Protect push endpoints with Laravel middleware:

    Route::post('/push', 'PushController@send')->middleware('auth:api');
    

Gotchas and Tips

Pitfalls

  1. Symfony Component Version Mismatch

    • Laravel 5.5+ uses Symfony 4.x, while this package may rely on Symfony 2/3 components. Test thoroughly or use a compatible version.
    • Fix: Pin Symfony components in composer.json or use a wrapper like spatie/symfony-messenger for compatibility.
  2. Certificate Management for APNs

    • APNs certificates expire and must be renewed. Store paths securely and log errors for manual intervention.
    • Tip: Use Laravel's env() for certificate paths and validate them on boot:
      if (!file_exists(env('APNS_CERT_PATH'))) {
          throw new \RuntimeException('APNs certificate not found.');
      }
      
  3. Token Expiry Device tokens can become invalid (e.g., app uninstalled). Implement retry logic or token validation:

    $push->setProvider('apns')
         ->setToken($token)
         ->setMessage('Test')
         ->send();
    if ($push->getResponse()->getStatusCode() === 400) {
        // Token invalid; remove from DB
        DB::table('users_devices')->where('device_token', $token)->delete();
    }
    
  4. Rate Limiting APNs and GCM have rate limits. Implement exponential backoff or queue delays:

    $push->setProvider('apns')->setMessage('Rate-limited test')->send();
    if ($push->getResponse()->getStatusCode() === 429) {
        sleep(10); // Retry after 10 seconds
    }
    

Debugging

  1. Enable Verbose Logging Configure Monolog to log push responses:

    $push->setProvider('gcm')->setDebug(true);
    // Logs will include raw responses and errors.
    
  2. Test with Sandbox Environments Use APNs sandbox for development:

    $push->setProvider('apns')
         ->setEnvironment('sandbox') // Default is 'production'
         ->setCertificatePath('/path/to/sandbox_cert.pem');
    
  3. Validate Payloads Ensure payloads comply with platform specs (e.g., APNs requires aps key for alerts):

    $push->setPayload([
        'aps' => [
            'alert' => 'Invalid without this key!',
            'sound' => 'default',
        ],
    ]);
    

Extension Points

  1. Custom Providers Extend AuthBucket\Push\Provider\AbstractProvider for unsupported platforms (e.g., Firebase Cloud Messaging):

    class FirebaseProvider extends AbstractProvider {
        public function send() {
            // Custom Firebase logic
        }
    }
    
  2. Model Managers Replace the default in-memory token manager with Doctrine or Eloquent:

    $app->bind('authbucket_push.model_manager.factory', function () {
        return new \AuthBucket\Push\Model\Manager\DoctrineManager(
            $this->get('doctrine')->getManager()
        );
    });
    
  3. Event Dispatching Trigger Laravel events after sending:

    $push->send();
    if ($push->getResponse()->isSuccessful()) {
        event(new PushSent($push->getTokens(), $push->getMessage()));
    }
    

Tips

  1. Use Laravel Queues for Reliability Offload push sending to queues to handle failures gracefully:

    Queue::push(new SendPushJob($tokens, $message));
    
  2. Monitor Delivery Status Log responses and track delivery metrics (e.g., success/failure rates):

    $response = $push->send();
    Log::info('Push response', [
        'status' => $response->getStatusCode(),
        'tokens' => $push->getTokens(),
    ]);
    
  3. Secure API Keys Never hardcode API keys. Use Laravel's .env:

    GCM_API_KEY=your_key_here
    APNS_CERT_PATH=/path/to/cert.pem
    
  4. Batch Size Optimization Test batch sizes to avoid timeouts (APNs recommends ≤ 200 tokens per request):

    $batchSize = 100;
    foreach (array_chunk($tokens, $batchSize) as $chunk) {
        $push->setTokens($chunk)->send();
    }
    
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.
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
spatie/mailcoach-vapor