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

Api Bundle Laravel Package

ciricihq/api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Symfony project via Composer:

    composer require ciricihq/api-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        CiriciHQ\ApiBundle\ApiBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default configuration:

    php bin/console ciricihq:api:install
    

    Update config/packages/ciricihq_api.yaml with your Firebase/APNs credentials (or other push providers).

  3. First Use Case: Sending a Push Notification Inject the PushNotificationService and send a test notification:

    use CiriciHQ\ApiBundle\Service\PushNotificationService;
    
    class MyController extends AbstractController
    {
        public function sendNotification(PushNotificationService $pushService): Response
        {
            $result = $pushService->send(
                'device_token_here',
                [
                    'title' => 'Hello!',
                    'body' => 'This is your first push notification.',
                ]
            );
    
            return $this->json($result);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Sending Notifications

    • Basic Usage:
      $pushService->send(
          'device_token',
          ['title' => 'Alert', 'body' => 'New message'],
          ['priority' => 'high', 'data' => ['key' => 'value']]
      );
      
    • Batch Sending:
      $pushService->sendBatch([
          'token1' => ['title' => 'Batch 1'],
          'token2' => ['title' => 'Batch 2'],
      ]);
      
  2. Handling Responses

    • Check $result->isSuccess() for success/failure.
    • Access raw response via $result->getResponse().
  3. Provider-Specific Logic

    • Extend AbstractPushProvider to support custom providers (e.g., WebPush, custom HTTP APIs).

Integration Tips

  • Symfony Messenger Integration Use the PushNotificationMessage class to queue notifications:

    $message = new PushNotificationMessage(
        'device_token',
        ['title' => 'Queued', 'body' => 'Delayed push']
    );
    $bus->dispatch($message);
    

    Configure the transport in config/packages/messenger.yaml:

    transports:
        push_notifications: { dsn: 'sync://' }
    
  • Event Listeners Subscribe to PushNotificationSentEvent to log or modify payloads:

    use CiriciHQ\ApiBundle\Event\PushNotificationSentEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class PushLogger implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [PushNotificationSentEvent::class => 'log'];
        }
    
        public function log(PushNotificationSentEvent $event): void
        {
            // Custom logic (e.g., logging, analytics)
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. Token Validation

    • Always validate device_token format before sending (e.g., regex for Firebase/APNs tokens).
    • Example:
      if (!preg_match('/^[a-zA-Z0-9\-_]{1,}$/', $token)) {
          throw new \InvalidArgumentException('Invalid token format.');
      }
      
  2. Rate Limiting

    • Firebase/APNs have quota limits.
    • Implement exponential backoff for failed batches:
      $pushService->sendWithRetry($token, $payload, 3); // Retry 3 times
      
  3. Configuration Overrides

    • Avoid hardcoding credentials. Use Symfony’s %env% or parameter bags:
      # config/packages/ciricihq_api.yaml
      ciricihq_api:
          providers:
              firebase:
                  project_id: '%env(FIREBASE_PROJECT_ID)%'
      

Debugging Tips

  • Enable Verbose Logging Set debug: true in config to log raw API responses:

    ciricihq_api:
        debug: true
    

    Check logs at var/log/dev.log.

  • Mock Providers for Testing Create a test provider by extending AbstractPushProvider and overriding send() to return mock responses:

    class MockPushProvider extends AbstractPushProvider
    {
        public function send(string $token, array $payload): PushResponse
        {
            return new PushResponse(true, ['mock' => 'response']);
        }
    }
    

    Bind it in services.yaml:

    services:
        CiriciHQ\ApiBundle\Service\PushNotificationService:
            arguments:
                $provider: '@mock_push_provider'
    

Extension Points

  1. Custom Payload Transformers Override PayloadTransformerInterface to modify payloads before sending:

    class CustomTransformer implements PayloadTransformerInterface
    {
        public function transform(array $payload): array
        {
            $payload['custom_key'] = 'custom_value';
            return $payload;
        }
    }
    

    Register it in services.yaml:

    services:
        CiriciHQ\ApiBundle\Transformer\PayloadTransformerInterface: '@custom_transformer'
    
  2. Async Processing For high-volume apps, offload to a queue (e.g., RabbitMQ, Redis):

    # config/packages/messenger.yaml
    transports:
        push_notifications: { dsn: '%env(MESSENGER_TRANSPORT_DSN)%' }
    routing:
        'CiriciHQ\ApiBundle\Message\PushNotificationMessage': push_notifications
    
  3. Webhook Validation If using APNs HTTP/2 or Firebase’s webhook, validate signatures:

    use CiriciHQ\ApiBundle\Validator\WebhookValidator;
    
    $validator = new WebhookValidator($request->getContent());
    if (!$validator->isValid($request->headers->get('auth-key'))) {
        throw new \RuntimeException('Invalid webhook signature.');
    }
    
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