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

Twitter Labs Laravel Package

spatie/twitter-labs

ReactPHP-powered PHP client for Twitter Developer Labs realtime endpoints, focused on the new filtered stream API as legacy streaming is deprecated. Works without deep React knowledge but integrates with event loops; easy migration from spatie/twitter-streaming-api.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/twitter-labs
    

    Ensure ext-curl and ext-json are enabled in your PHP environment.

  2. Configuration: Publish the config file:

    php artisan vendor:publish --provider="Spatie\TwitterLabs\TwitterLabsServiceProvider"
    

    Update .env with your Twitter API Bearer Token (from Twitter Developer Portal):

    TWITTER_LAB_BEARER_TOKEN=your_bearer_token_here
    
  3. First Use Case: Stream public tweets in real-time:

    use Spatie\TwitterLabs\TwitterLabs;
    
    $stream = TwitterLabs::streamPublicTweets();
    $stream->on('tweet', function ($tweet) {
        // Handle incoming tweet (e.g., log, store in DB, or process)
        \Log::info('New tweet:', $tweet);
    });
    

    Run the stream in a Laravel command or controller (requires async handling).


Where to Look First

  • README.md: Covers basic usage and endpoints.
  • config/twitter-labs.php: Customize timeouts, retries, and logging.
  • app/Console/Commands/: Example: Create a StreamTweetsCommand to encapsulate streaming logic.

Implementation Patterns

Core Workflows

  1. Streaming Tweets:

    • Use TwitterLabs::streamPublicTweets() for real-time public tweets.
    • Filter streams with parameters (e.g., languages, locations):
      $stream = TwitterLabs::streamPublicTweets(['lang' => 'en']);
      
  2. Handling Events:

    • Attach listeners to events (e.g., tweet, connect, disconnect):
      $stream->on('tweet', fn($tweet) => $this->processTweet($tweet));
      $stream->on('error', fn($error) => \Log::error($error));
      
  3. Async Processing:

    • Offload heavy processing to queues (e.g., store tweets in a database):
      $stream->on('tweet', function ($tweet) {
          dispatch(new StoreTweetJob($tweet));
      });
      
  4. Laravel Integration:

    • Commands: Run streams in the background:
      // app/Console/Commands/StreamTweets.php
      public function handle() {
          $stream = TwitterLabs::streamPublicTweets();
          $this->listenForEvents($stream);
      }
      
    • Events: Dispatch Laravel events for cross-service communication:
      $stream->on('tweet', fn($tweet) => event(new TweetReceived($tweet)));
      
  5. Reconnect Logic:

    • Implement exponential backoff for reconnects:
      $stream->on('disconnect', function () use ($stream) {
          sleep(2 ** $this->retryCount++);
          $stream->connect();
      });
      

Advanced Patterns

  1. Custom Endpoints:

    • Extend the package for unsupported Labs endpoints by creating a custom client:
      use Spatie\TwitterLabs\TwitterLabsClient;
      
      class CustomTwitterLabsClient extends TwitterLabsClient {
          public function customEndpoint($params) {
              return $this->request('GET', '/custom-endpoint', $params);
          }
      }
      
  2. Rate Limiting:

    • Monitor rate limits via the limit event:
      $stream->on('limit', fn($limit) => \Log::warning("Rate limit hit: {$limit->resource}"));
      
  3. Testing:

    • Mock the client in tests using Laravel’s HTTP testing:
      $this->mock(TwitterLabsClient::class, function ($mock) {
          $mock->shouldReceive('streamPublicTweets')
               ->andReturnSelf()
               ->shouldReceive('on')
               ->andReturnSelf();
      });
      

Gotchas and Tips

Pitfalls

  1. Async Blocking:

    • Avoid blocking calls (e.g., sleep()) in event handlers—use ReactPHP’s Timer for delays:
      use React\EventLoop\Timer\Timer;
      
      $stream->on('disconnect', function () use ($loop) {
          $loop->addTimer(2, fn() => $this->reconnect());
      });
      
  2. Bearer Token Leaks:

    • Never hardcode tokens. Use Laravel’s .env and validate the token exists in config/twitter-labs.php:
      'bearer_token' => env('TWITTER_LAB_BEARER_TOKEN') ?: throw new \RuntimeException('Bearer token not set'),
      
  3. Deprecated Endpoints:

    • Twitter Labs endpoints are experimental. Monitor Twitter’s Labs docs for changes and update your code accordingly.
  4. Memory Leaks:

    • Ensure streams are properly closed in Laravel’s terminate() or command cleanup:
      public function terminate() {
          $this->stream->close();
      }
      

Debugging Tips

  1. Enable Logging:

    • Configure logging in config/twitter-labs.php:
      'log' => [
          'enabled' => true,
          'channel' => 'single',
      ],
      
    • Check logs for connection issues or malformed responses.
  2. ReactPHP Event Loop:

    • If streams hang, ensure no other async operations (e.g., queues) are blocking the loop. Use React\EventLoop\Loop::get() to inspect the loop state.
  3. HTTP Errors:

    • Handle 4xx/5xx responses gracefully:
      $stream->on('error', function ($error) {
          if ($error->getCode() === 429) {
              // Retry logic for rate limits
          }
      });
      

Extension Points

  1. Custom Middleware:

    • Add middleware to modify requests/responses:
      $client->withMiddleware(function ($request) {
          $request->headers->set('X-Custom-Header', 'value');
      });
      
  2. Event Broadcasting:

    • Broadcast tweet events to Pusher/Redis for real-time frontend updates:
      $stream->on('tweet', fn($tweet) => broadcast(new TweetBroadcast($tweet))->toOthers());
      
  3. Database Sync:

    • Use Laravel’s observers or model events to sync tweets with your DB:
      class TweetObserver {
          public function saved(Tweet $tweet) {
              // Trigger a webhook or update cache
          }
      }
      
  4. Testing Labs Features:

    • Use the package’s TwitterLabs::fake() for unit tests:
      TwitterLabs::fake([
          'tweets' => [/* mock 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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport