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

Pusher Bundle Laravel Package

bentools/pusher-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Run:

    composer require bentools/pusher-bundle
    

    (Note: This bundle is deprecated; consider bentools/webpush-bundle instead.)

  2. Register the Bundle Add to config/bundles.php (Symfony 4+):

    return [
        // ...
        BenTools\PusherBundle\BenToolsPusherBundle::class => ['all' => true],
    ];
    
  3. Configure Handlers Define push service handlers in config/services.yaml:

    services:
        BenTools\Pusher\Model\Handler\MozillaHandler:
            arguments:
                $client: '@http_client'
        BenTools\Pusher\Model\Handler\GoogleCloudMessagingHandler:
            arguments:
                $client: '@http_client'
                $apiKey: '%env(GCM_API_KEY)%'
    
  4. Database Schema Update your database to store subscriptions:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  5. Route Registration Add to config/routes.yaml:

    webpush_bundle:
        resource: "@BenToolsPusherBundle/Resources/config/routing.yaml"
        prefix: /webpush
    
  6. Frontend Integration Embed the JS client in your Twig template (ensure HTTPS/localhost and authenticated user):

    <script src="{{ asset('bundles/bentoolspusher/js/pushClient.js') }}"></script>
    

Implementation Patterns

Workflow: Sending Push Notifications

  1. Register a Subscription The /webpush/registration endpoint handles subscription registration via the JS client.

  2. Trigger Notifications Use the service container to dispatch notifications:

    // Example: Send to Mozilla subscribers
    $mozillaHandler = $container->get('BenTools\Pusher\Model\Handler\MozillaHandler');
    $mozillaHandler->send($subscription, $payload);
    
  3. Batch Processing Fetch subscriptions and loop through them:

    $subscriptions = $entityManager->getRepository(Subscription::class)->findAll();
    foreach ($subscriptions as $subscription) {
        $handler = $this->getHandlerForSubscription($subscription);
        $handler->send($subscription, $payload);
    }
    

Integration Tips

  • Symfony Messenger Integrate with Messenger for async processing:

    # config/packages/messenger.yaml
    framework:
        messenger:
            transports:
                push_notifications: '%env(MESSENGER_TRANSPORT_DSN)%'
            routing:
                'BenTools\Pusher\Model\Message\PushNotificationMessage': push_notifications
    
  • Event-Driven Dispatch events (e.g., UserRegisteredEvent) and listen to send push notifications:

    // Event subscriber
    public function onUserRegistered(UserRegisteredEvent $event) {
        $this->pushService->sendWelcomeNotification($event->getUser());
    }
    
  • Twig Extensions Create a Twig extension to simplify frontend integration:

    // src/Twig/PushExtension.php
    class PushExtension extends AbstractExtension {
        public function getFunctions() {
            return [
                new TwigFunction('push_subscribe', [$this, 'renderSubscribeButton']),
            ];
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning This bundle is deprecated in favor of bentools/webpush-bundle. Migrate if possible.

  2. HTTPS Requirement Push notifications only work over HTTPS (or localhost for development). Configure your server to enforce HTTPS.

  3. Service Configuration

    • Ensure guzzle.client.default (or http_client) is configured in services.yaml.
    • API keys (e.g., GCM) must be set in .env:
      GCM_API_KEY=your_key_here
      
  4. Database Schema The bundle expects a Subscription entity. If you customize it, ensure the endpoint, keys, and user fields are preserved.

  5. CORS Issues The /webpush/registration endpoint may trigger CORS errors if not configured. Add to your .htaccess or server config:

    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "POST, OPTIONS"
    

Debugging

  • Check Subscriptions Verify subscriptions are stored in the database:

    php bin/console doctrine:query:sql "SELECT * FROM subscription"
    
  • Log Payloads Enable debug mode to log push payloads:

    # config/packages/monolog.yaml
    monolog:
        handlers:
            main:
                level: debug
    
  • Test with Postman Manually test the /webpush/registration endpoint to ensure it returns 201 Created.

Extension Points

  1. Custom Handlers Extend BenTools\Pusher\Model\Handler\AbstractHandler to support new providers (e.g., Firebase Cloud Messaging):

    class FirebaseHandler extends AbstractHandler {
        public function send(Subscription $subscription, array $payload) {
            // Custom logic
        }
    }
    
  2. Subscription Validation Override the SubscriptionValidator to add custom rules (e.g., domain whitelisting):

    class CustomSubscriptionValidator implements SubscriptionValidatorInterface {
        public function isValid(Subscription $subscription) {
            return str_contains($subscription->getEndpoint(), 'yourdomain.com');
        }
    }
    
  3. Payload Transformers Modify payloads before sending using a decorator pattern:

    $handler->setPayloadTransformer(function (array $payload) {
        $payload['custom_field'] = 'value';
        return $payload;
    });
    
  4. Event Listeners Listen for PushNotificationSentEvent to log or analyze sent notifications:

    // src/EventListener/PushNotificationListener.php
    class PushNotificationListener {
        public function onNotificationSent(PushNotificationSentEvent $event) {
            // Log or process
        }
    }
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php