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

Simple Client Laravel Package

enqueue/simple-client

Enqueue Simple Client combines Enqueue client classes with Symfony components into an easy-to-use SimpleClient facade for sending and consuming messages via queues. Part of the Enqueue ecosystem; see docs and support via the project site.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require enqueue/simple-client
    

    Ensure enqueue/enqueue and symfony/config are also installed (they are dependencies).

  2. Basic Setup: Create a SimpleClient instance with a connection to your broker (e.g., RabbitMQ):

    use Enqueue\SimpleClient\SimpleClient;
    
    $client = new SimpleClient();
    $connection = $client->createConnection(['host' => 'amqp://guest:guest@localhost']);
    
  3. First Use Case: Publish a message to a queue:

    $producer = $connection->createProducer();
    $producer->send(new \Enqueue\AmqpExt\Message('Hello, Queue!'));
    
  4. Consume Messages:

    $consumer = $connection->createConsumer('your_queue_name');
    $consumer->setMessageHandler(function (\Enqueue\Message $message) {
        // Process message
        return \Enqueue\Client\FunctionalContext::ACK;
    });
    $consumer->consume();
    
  5. Laravel Integration (Optional): Register the SimpleClient as a queue driver in config/queue.php:

    'connections' => [
        'enqueue' => [
            'driver' => 'enqueue',
            'client' => \Enqueue\SimpleClient\SimpleClient::class,
            'config' => [
                'dsn' => env('QUEUE_CONNECTION_DSN', 'amqp://guest:guest@localhost'),
            ],
        ],
    ],
    

Implementation Patterns

Usage Patterns

  1. Facade-Based Dispatching: Use SimpleClient as a facade to abstract queue operations:

    $client = new SimpleClient();
    $connection = $client->createConnection(['host' => env('QUEUE_DSN')]);
    
    // Publish a job (e.g., Laravel Job)
    $producer = $connection->createProducer();
    $producer->send(new \App\Jobs\ProcessPodcast());
    
  2. Laravel Job Integration: Extend Laravel’s Job class and dispatch via the enqueue driver:

    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class ProcessPodcast implements ShouldQueue
    {
        use Queueable;
    
        public $queue = 'enqueue';
    }
    
    // Dispatch
    ProcessPodcast::dispatch();
    
  3. Consumer Workflows: Run consumers as Laravel commands or standalone scripts:

    // In a Laravel Artisan command
    public function handle()
    {
        $client = new SimpleClient();
        $connection = $client->createConnection(['host' => env('QUEUE_DSN')]);
        $consumer = $connection->createConsumer('enqueue');
    
        $consumer->setMessageHandler(function ($message) {
            // Process message
            return \Enqueue\Client\FunctionalContext::ACK;
        });
    
        $consumer->consume();
    }
    
  4. Multi-Transport Configuration: Switch transports dynamically via config (e.g., amqp, redis, fs):

    $config = [
        'dsn' => env('QUEUE_DSN', 'amqp://guest:guest@localhost'),
        // For Redis: 'dsn' => 'redis://localhost'
    ];
    $connection = $client->createConnection($config);
    
  5. Error Handling and Retries: Use Enqueue’s retry mechanisms:

    $producer = $connection->createProducer();
    $producer->setMessage(new \Enqueue\AmqpExt\Message('Retry me!'))
             ->setDelay(1000) // Delay in ms
             ->setPriority(5); // Priority level
    

Workflows

  1. Background Job Processing:

    • Dispatch Laravel jobs to the enqueue driver.
    • Run consumers in the background (e.g., via enqueue:consume or Laravel’s queue:work).
  2. Event-Driven Architecture:

    • Publish domain events to queues and consume them in microservices.
    • Example: User signup event triggers email and notification services.
  3. Batch Processing:

    • Use bulk producers to send multiple messages efficiently:
      $producer = $connection->createProducer();
      $producer->sendBulk([
          new \Enqueue\AmqpExt\Message('Batch job 1'),
          new \Enqueue\AmqpExt\Message('Batch job 2'),
      ]);
      
  4. Delayed Jobs:

    • Schedule jobs to run after a delay:
      $producer->setDelay(3600000); // 1 hour in ms
      $producer->send(new \Enqueue\AmqpExt\Message('Delayed job'));
      

Integration Tips

  1. Laravel Service Provider: Bind SimpleClient to Laravel’s container for dependency injection:

    public function register()
    {
        $this->app->singleton(\Enqueue\SimpleClient\SimpleClient::class, function ($app) {
            return new \Enqueue\SimpleClient\SimpleClient();
        });
    }
    
  2. Environment Configuration: Use Laravel’s .env to manage queue connections:

    QUEUE_CONNECTION_DSN=amqp://guest:guest@localhost
    QUEUE_CONNECTION=enqueue
    
  3. Monitoring: Integrate with Laravel Horizon or custom monitoring:

    $stats = $connection->getStats();
    // Log or expose stats via API
    
  4. Testing: Use Enqueue’s test utilities or mock the SimpleClient in PHPUnit:

    $mockConnection = $this->createMock(\Enqueue\Client\Connection::class);
    $client = new SimpleClient();
    $client->setConnection($mockConnection);
    

Gotchas and Tips

Pitfalls

  1. Connection Management:

    • Issue: Forgetting to close connections can lead to resource leaks.
    • Fix: Use try-finally blocks or dependency injection with Laravel’s container to ensure connections are closed:
      try {
          $connection = $client->createConnection(['host' => 'amqp://...']);
          // Use connection
      } finally {
          $connection->close();
      }
      
  2. Message Serialization:

    • Issue: Messages must be serializable. Laravel jobs are serializable by default, but custom objects may fail.
    • Fix: Implement Serializable or use JSON serialization:
      $message = new \Enqueue\AmqpExt\Message(json_encode($data));
      
  3. Transport-Specific Quirks:

    • RabbitMQ: Ensure the exchange and queue exist before publishing.
    • Redis: Configure proper TTL for messages to avoid memory bloat.
    • Filesystem: Monitor disk space for enqueue/fs transport.
  4. Laravel Queue Driver Conflicts:

    • Issue: Mixing enqueue driver with Laravel’s native drivers (e.g., database) may cause unexpected behavior.
    • Fix: Stick to one driver per queue or use separate queue connections.
  5. Consumer Blocking:

    • Issue: Consumers may block indefinitely if not handled properly.
    • Fix: Use non-blocking consumers or implement timeouts:
      $consumer->consume(1000); // Timeout in ms
      

Debugging

  1. Connection Errors:

    • Verify DSN format (e.g., amqp://user:pass@host:port/vhost).
    • Check broker service status (e.g., rabbitmqctl status for RabbitMQ).
  2. Message Not Delivered:

    • Ensure the queue exists and the consumer is bound to it.
    • Check for exceptions in the message handler (e.g., unhandled errors).
  3. Performance Issues:

    • Monitor queue depth and consumer lag.
    • Adjust prefetch count for consumers:
      $consumer->setPrefetchCount(10); // Limit unacknowledged messages
      
  4. Logging:

    • Enable debug logging for Enqueue:
      $client->setLogger(new \Monolog\Logger('enqueue', [new \Monolog\Handler\StreamHandler('php://stderr')]));
      

Config Quirks

  1. DSN Format:

    • Use amqp:// for RabbitMQ, redis:// for Redis, etc.
    • Example: amqp://guest:guest@localhost:5672/%2f (URL-encoded /).
  2. Default Exchange:

    • If not specified, messages are sent to the default exchange.
    • Explicitly set an exchange for clarity:
      $producer->setExchange('your_exchange');
      
  3. Priority Queues:

    • Requires RabbitMQ with priority plugin enabled.
    • Set priority when sending:
      $producer->setPriority(5);
      

Extension Points

  1. Custom Message Classes:

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.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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