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

Gps Messenger Bundle Laravel Package

petitpress/gps-messenger-bundle

Laravel bundle for GPS Messenger: send and receive location-based messages, integrate tracking updates, and manage messaging workflows via simple configuration. Designed to drop into existing apps with minimal setup for GPS-enabled notifications and events.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Bundle

    composer require petitpress/gps-messenger-bundle google/cloud-pubsub
    

    Add to config/bundles.php:

    return [
        Petitpress\GpsMessengerBundle\PetitpressGpsMessengerBundle::class => ['all' => true],
    ];
    
  2. Configure Google Cloud Credentials Store your service account JSON key in a secure location (e.g., config/google-credentials.json) and set the environment variable:

    export GOOGLE_APPLICATION_CREDENTIALS="%kernel.project_dir%/config/google-credentials.json"
    
  3. Define a Message Class Create a simple message handler (e.g., for GPS tracking events):

    namespace App\Message;
    
    class GpsTrackingEvent
    {
        public function __construct(
            public string $deviceId,
            public float $latitude,
            public float $longitude,
            public \DateTimeImmutable $timestamp
        ) {}
    }
    
  4. Configure Messenger Transport Update config/packages/messenger.yaml:

    framework:
        messenger:
            transports:
                gps_pubsub:
                    dsn: "gps://your-project-id/your-topic"
                    options:
                        subscription: "your-subscription"
                        client:
                            project_id: "your-project-id"
                            key_file: "%kernel.project_dir%/config/google-credentials.json"
            routing:
                'App\Message\GpsTrackingEvent': gps_pubsub
    
  5. Dispatch a Test Message

    use App\Message\GpsTrackingEvent;
    use Symfony\Component\Messenger\MessageBusInterface;
    
    public function __construct(private MessageBusInterface $bus) {}
    
    public function handleTrackingEvent()
    {
        $this->bus->dispatch(new GpsTrackingEvent(
            'device-123',
            37.7749,
            -122.4194,
            new \DateTimeImmutable()
        ));
    }
    
  6. Consume Messages Run the Messenger worker:

    php bin/console messenger:consume gps_pubsub -vv
    

Implementation Patterns

Core Workflows

  1. Pub/Sub Transport Integration

    • Use the gps:// DSN format for all Pub/Sub transports.
    • Example DSN: gps://project-id/topic-name?subscription=sub-name.
    • Configure retry strategies in messenger.yaml:
      messenger:
          transports:
              gps_pubsub:
                  dsn: "gps://..."
                  retry_strategy:
                      max_retries: 3
                      delay: 1000
                      multiplier: 2
      
  2. Message Normalization

    • The bundle auto-normalizes GPS payloads (e.g., Garmin/GPS-specific formats) into standard GpsTrackingEvent objects.
    • Extend normalization with custom middleware:
      namespace App\Middleware;
      
      use Symfony\Component\Messenger\Attribute\AsMessageHandler;
      use Symfony\Component\Messenger\Handler\Middleware\StackInterface;
      
      class NormalizeGpsPayloadMiddleware
      {
          public function __invoke($message, StackInterface $next)
          {
              // Custom logic to transform raw GPS data
              return $next($message);
          }
      }
      
  3. Routing by Message Type

    • Route different message types to different Pub/Sub topics/subscriptions:
      messenger:
          routing:
              'App\Message\GpsTrackingEvent': gps_pubsub
              'App\Message\DeviceAlert': gps_pubsub_alerts
      
    • Define multiple transports in messenger.yaml:
      transports:
          gps_pubsub:
              dsn: "gps://project-id/tracking-topic"
          gps_pubsub_alerts:
              dsn: "gps://project-id/alerts-topic"
      
  4. Async Processing with Workers

    • Run dedicated workers for Pub/Sub subscriptions:
      php bin/console messenger:consume gps_pubsub -vv --limit=10
      
    • Use supervisor or systemd to manage workers in production:
      [program:gps-worker]
      command=php /path/to/bin/console messenger:consume gps_pubsub -vv
      autostart=true
      autorestart=true
      
  5. Error Handling and Retries

    • Configure failed message handling in messenger.yaml:
      messenger:
          failure_transport: failed
          transports:
              failed:
                  dsn: "doctrine://default"
      
    • Add custom failure handlers for Pub/Sub-specific errors:
      use Symfony\Component\Messenger\Attribute\AsMessageHandler;
      use Symfony\Component\Messenger\MessageBusInterface;
      use Google\Cloud\PubSub\PubSubClientInterface;
      
      class PubSubFailureHandler
      {
          public function __construct(private PubSubClientInterface $pubsub) {}
      
          public function __invoke($failedMessage)
          {
              // Log or dead-letter Pub/Sub-specific failures
              $this->pubsub->publish(...);
          }
      }
      

Integration Tips

  1. Laravel-Specific Adaptations

    • Use Laravel’s service container to bind the Messenger bus:
      $this->app->bind(MessageBusInterface::class, function ($app) {
          return $app->make('messenger.bus.default');
      });
      
    • Publish config to Laravel’s config/petitpress_gps_messenger.php:
      return [
          'client' => [
              'project_id' => env('GOOGLE_CLOUD_PROJECT'),
              'key_file' => env('GOOGLE_APPLICATION_CREDENTIALS'),
          ],
          'transports' => [
              'gps_async' => [
                  'dsn' => 'gps://'.env('GOOGLE_CLOUD_PROJECT').'/'.env('PUBSUB_TOPIC'),
                  'options' => [
                      'subscription' => env('PUBSUB_SUBSCRIPTION'),
                  ],
              ],
          ],
      ];
      
  2. Testing with Local Pub/Sub Emulator

    • Use Google Cloud’s Pub/Sub Emulator for local testing:
      docker run -p 8085:8085 gcr.io/google.com/cloudsdktool/cloud-sdk:latest \
          gcloud beta emulators pubsub start --host-port=0.0.0.0:8085
      
    • Configure the emulator in messenger.yaml:
      transports:
          gps_pubsub:
              dsn: "gps://emulator/emulator-topic"
              options:
                  emulator_host: "localhost:8085"
      
  3. Monitoring and Observability

    • Integrate with Laravel Telescope or Symfony Profiler to track message flow:
      use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
      
      class LoggingMiddleware
      {
          public function __invoke($message, StackInterface $next)
          {
              \Log::info('Message dispatched', ['message' => get_class($message)]);
              return $next($message);
          }
      }
      
    • Use Google Cloud Operations for Pub/Sub metrics (e.g., message volume, latency).
  4. Serverless Deployment (Cloud Functions)

    • Deploy Laravel workers as Google Cloud Functions for auto-scaling:
      # cloudbuild.yaml
      steps:
        - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
          args: ['gcloud', 'functions', 'deploy', 'gps-worker',
                  '--runtime', 'php81',
                  '--trigger-topic', 'your-topic',
                  '--entry-point', 'handlePubSubMessage']
      
    • Handle Pub/Sub messages in a Cloud Function:
      use Google\Cloud\PubSub\PubSubMessage;
      
      function handlePubSubMessage(PubSubMessage $message) {
          $data = json_decode($message->data(), true);
          // Dispatch to Laravel Messenger via HTTP or direct SDK call
      }
      

Gotchas and Tips

Pitfalls

  1. Authentication Issues

    • Problem: Google\Auth\Exception\InvalidCredentialsException if credentials are invalid or expired.
    • Fix:
      • Ensure GOOGLE_APPLICATION_CREDENTIALS points to a valid JSON key file.
      • Verify the service account has Pub/Sub Publisher/Subscriber roles in IAM.
      • Rotate credentials periodically and update the config.
  2. Message Serialization Errors

    • Problem: Non-serializable objects (e.g., closures, resources) cause SerializationException.
    • Fix:
      • Use Symfony’s serializer or JMS Serializer for complex objects.
      • Implement __serialize()/`__unserialize
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle