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

Ably Php Laravel Package

ably/ably-php

Ably Pub/Sub PHP SDK for building realtime messaging apps in PHP. Publish/subscribe, message history, presence, and push via Ably’s scalable platform. Install with Composer and use REST APIs to connect, manage channels, and publish messages.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ably/ably-php
    

    For Laravel, prefer ably/ably-php-laravel for seamless integration.

  2. First Use Case: Publishing a Message

    use Ably\Lib\Ably;
    
    $ably = new Ably\AblyRest([
        'key' => env('ABLY_API_KEY'), // Use Laravel's .env
        'clientId' => 'laravel-app-' . Str::uuid(),
    ]);
    
    $channel = $ably->channel('notifications');
    $channel->publish('user.created', ['id' => 123, 'name' => 'John Doe']);
    
  3. Where to Look First


Implementation Patterns

Core Workflows

  1. Channel Management

    // Attach to a channel (for subscriptions)
    $channel = $ably->channel('live-updates');
    $channel->attach();
    
    // Detach when done
    $channel->detach();
    
  2. Message Handling

    // Subscribe to events
    $channel->subscribe('user.updated', function ($message) {
        Log::info('Received update:', $message->data);
    });
    
    // Publish with metadata
    $channel->publish('order.placed', ['orderId' => 456], [
        'extras' => ['priority' => 'high'],
        'ttl' => 3600, // 1-hour TTL
    ]);
    
  3. Batch Operations

    // Batch publish to multiple channels
    $batch = $ably->batch();
    $batch->publish('channel1', 'event1', ['data' => '...']);
    $batch->publish('channel2', 'event2', ['data' => '...']);
    $batch->send();
    
  4. Presence Management

    $presence = $channel->presence;
    $presence->update(['status' => 'online']);
    $presence->subscribe(function ($presenceEvent) {
        Log::debug('User joined:', $presenceEvent->clientId);
    });
    
  5. Push Notifications

    // Configure push for a device
    $push = $ably->push;
    $push->admin->deviceRegistrations->save([
        'deviceId' => 'device123',
        'deviceSecret' => 'secret',
        'deviceType' => 'ios',
    ]);
    

Laravel Integration Tips

  • Service Provider Binding:

    // config/ably.php
    'key' => env('ABLY_API_KEY'),
    'clientId' => env('ABLY_CLIENT_ID', 'laravel-app-' . Str::uuid()),
    
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(AblyRest::class, function ($app) {
            return new AblyRest(config('ably'));
        });
    }
    
  • Broadcasting Events:

    // Event class
    class UserCreated implements ShouldBroadcast
    {
        public $user;
        public function broadcastOn()
        {
            return new Channel('notifications');
        }
    }
    
    // Controller
    event(new UserCreated($user));
    
  • Queue Workers: Use Laravel Queues to defer Ably operations:

    Dispatch(new PublishAblyMessage($channel, $event, $data));
    

Gotchas and Tips

Pitfalls

  1. Authentication Quirks

    • Token Auth: If using token auth, ensure clientId matches the token’s clientId to avoid 403 errors.
      $ably = new AblyRest([
          'authUrl' => 'https://your-auth-service.com/token',
          'clientId' => 'user123',
      ]);
      
    • Basic Auth: Avoid mixing clientId with basic auth unless explicitly required (see #102).
  2. Protocol Version

    • SDK 1.1.9+ uses Protocol 2.0 (default). Older versions (<1.1.9) are deprecated.
    • Force Protocol 1.1 for legacy systems:
      $ably = new AblyRest(['key' => '...', 'protocol' => '1.1']);
      
  3. Message Serialization

    • MsgPack: Enabled by default for batch operations. Disable if compatibility issues arise:
      $ably = new AblyRest(['key' => '...', 'useMsgPack' => false]);
      
  4. Connection Resilience

    • Fallback Hosts: The SDK remembers failed hosts (e.g., eu-west-1). Clear cache if needed:
      $ably->setOption('rememberedHost', null);
      
    • Timeouts: Default timeout is 10s. Increase for unstable networks:
      $ably->setOption('timeout', 30); // 30s
      
  5. Idempotency

    • Idempotent Publishing: Requires SDK 1.2+ (not in this package). Use unique IDs for retries:
      $channel->publish('event', $data, ['idempotent' => true, 'id' => uniqid()]);
      

Debugging Tips

  1. Enable Logging

    $ably->setOption('logLevel', Ably\Lib\LogLevel::DEBUG);
    $ably->setOption('logger', new Monolog\Logger('ably'));
    
  2. HTTP Headers

    • Verify headers like X-Ably-Lib and Ably-Agent are set:
      $ably->setOption('headers', ['X-Custom-Header' => 'value']);
      
  3. Common Errors

    • 401 Unauthorized: Check API key or token.
    • 404 Not Found: Validate channel names (case-sensitive).
    • 429 Too Many Requests: Implement exponential backoff:
      try {
          $channel->publish(...);
      } catch (Ably\Lib\Exception\RateLimitExceeded $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      

Extension Points

  1. Custom HTTP Client Replace the default Guzzle client for advanced use cases:

    $ably = new AblyRest([
        'key' => '...',
        'httpClient' => new CustomHttpClient(),
    ]);
    
  2. Event Hooks Extend the SDK’s event system:

    $ably->on('messageReceived', function ($message) {
        // Pre-process messages
    });
    
  3. Message Transformers Serialize/deserialize messages before sending/receiving:

    $channel->setSerializer(new JsonSerializer());
    
  4. Laravel Broadcasting Extend the ably/laravel-broadcaster for custom event handling:

    // app/Providers/BroadcastServiceProvider.php
    public function boot()
    {
        $this->app->make(AblyBroadcaster::class)->extend('ably', function () {
            return new CustomAblyBroadcaster();
        });
    }
    

Laravel-Specific Gotchas

  1. Environment Variables

    • Store ABLY_API_KEY in .env:
      ABLY_API_KEY=your_key_here
      ABLY_CLIENT_ID=laravel-app-${APP_UUID}
      
  2. Broadcasting Failures

    • Queue Monitoring: Use Laravel Horizon to track failed Ably broadcasts.
    • Retry Logic: Implement ShouldQueue with retryAfter() for transient failures.
  3. Presence Channel Conflicts

    • Avoid naming presence channels the same as broadcast channels (e.g., users vs. presence:users).
  4. Testing

    • Use Ably\Lib\Mock\AblyMock for unit tests:
      $mock = new AblyMock();
      $mock->channel('test')->publish('event', ['data' => 'test']);
      $this->assertEquals(['data' => 'test'], $mock->lastPublishedMessage()->data);
      
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