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 Client Laravel Package

desarrolla2/twitter-client

Independent PHP Twitter client for fetching a user’s tweets via RSS. Supports simple usage or optional caching through desarrolla2/cache and RSSClient. Install via Composer, set a screen name, and fetch recent tweets quickly.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require desarrolla2/twitter-client
    

    Ensure desarrolla2/rss-client (dependency) is also installed.

  2. First Use Case Fetch tweets from a user without caching (for testing or low-frequency use):

    use Desarrolla2\TwitterClient\TwitterClient;
    
    $client = new TwitterClient();
    $client->setScreenName('laravelphp'); // Replace with target username
    $tweets = $client->fetch(5); // Fetch 5 most recent tweets
    
  3. Where to Look First

    • TwitterClient class: Core functionality for fetching tweets.
    • setScreenName(): Configure the target Twitter handle.
    • fetch($limit): Retrieve tweets (returns raw data; see Implementation Patterns for parsing).
    • RSSCacheClient: For caching (requires desarrolla2/cache package).

Implementation Patterns

Core Workflows

  1. Fetching Tweets

    • Basic Usage:
      $client = new TwitterClient();
      $client->setScreenName('laravelnews');
      $tweets = $client->fetch(10); // Array of tweet objects (see structure below).
      
    • Parsing Output: The fetch() method returns an array of tweet objects with properties like:
      $tweet->id, $tweet->text, $tweet->created_at, $tweet->user
      
      Example loop:
      foreach ($tweets as $tweet) {
          echo $tweet->user->screen_name . ': ' . $tweet->text . "\n";
      }
      
  2. Caching Integration

    • Setup Cache Adapter (e.g., Redis, File):
      use Desarrolla2\RSSClient\RSSCacheClient;
      use Desarrolla2\Cache\Adapters\RedisAdapter;
      
      $cache = new RSSCacheClient(new RedisAdapter());
      $client = new TwitterClient($cache);
      $client->setScreenName('laravel');
      $tweets = $client->fetch(5); // Uses cache if available.
      
    • Cache TTL: Configure via RSSCacheClient (default: 300 seconds).
      $cache->setTTL(1800); // Cache for 30 minutes.
      
  3. Error Handling

    • Wrap calls in try-catch for network/API issues:
      try {
          $tweets = $client->fetch(10);
      } catch (\Exception $e) {
          Log::error("Twitter fetch failed: " . $e->getMessage());
          // Fallback: Return cached data or empty array.
      }
      
  4. Laravel Integration

    • Service Provider: Bind the client to Laravel’s IoC container in AppServiceProvider:
      public function register() {
          $this->app->singleton(TwitterClient::class, function ($app) {
              $cache = new RSSCacheClient(new \Desarrolla2\Cache\Adapters\FileAdapter());
              return new TwitterClient($cache);
          });
      }
      
    • Facade (Optional): Create a facade for cleaner syntax:
      // app/Facades/Twitter.php
      namespace App\Facades;
      use Illuminate\Support\Facades\Facade;
      class Twitter extends Facade { protected static function getFacadeAccessor() { return 'twitter'; } }
      
      Register in config/app.php:
      'twitter' => \Desarrolla2\TwitterClient\TwitterClient::class,
      
  5. Batch Processing

    • Fetch tweets in chunks (e.g., for analytics):
      $client->setScreenName('laravel');
      $allTweets = [];
      $limit = 100;
      $offset = 0;
      do {
          $tweets = $client->fetch($limit, $offset);
          $allTweets = array_merge($allTweets, $tweets);
          $offset += $limit;
      } while (!empty($tweets));
      

Gotchas and Tips

Pitfalls

  1. No API Key Authentication

    • This package uses Twitter’s public RSS feed (e.g., https://twitter.com/{screen_name}.rss).
    • Limitations:
      • No access to protected tweets or extended metadata (e.g., retweet counts, likes).
      • Rate limits apply (Twitter may throttle RSS feeds).
    • Workaround: For full API access, use the official Twitter API v2 with a package like abraham/twitteroauth.
  2. Caching Dependencies

    • The cache system (RSSCacheClient) requires desarrolla2/cache.
    • Issue: If the cache package is missing, the client may throw undefined class errors.
    • Fix: Ensure both packages are installed:
      composer require desarrolla2/twitter-client desarrolla2/cache
      
  3. Data Format Quirks

    • Tweets returned by fetch() are not standardized JSON/arrays but custom objects.
    • Tip: Inspect the first tweet’s properties to understand the structure:
      print_r(get_object_vars($tweets[0]));
      
  4. Performance

    • Without Cache: Each fetch() makes an HTTP request to Twitter’s RSS feed.
      • Slow for high-traffic sites: Cache aggressively (e.g., 5-minute TTL).
    • With Cache: Still depends on desarrolla2/cache performance. Test with your adapter (Redis > File).
  5. Deprecation Risk

    • Twitter may deprecate RSS feeds or change their format.
    • Mitigation: Monitor Twitter’s API updates and consider a fallback (e.g., store historical data in a DB).

Debugging Tips

  1. Enable Verbose Logging

    • Add this to inspect HTTP requests (if the package supports it):
      $client->setDebug(true);
      
    • Check for errors in Twitter’s RSS feed URL (e.g., https://twitter.com/{screen_name}.rss).
  2. Validate Screen Names

    • Ensure setScreenName() uses a valid Twitter handle (no spaces, correct case).
    • Example of validation:
      if (!preg_match('/^[a-z0-9_]+$/i', $screenName)) {
          throw new \InvalidArgumentException("Invalid Twitter screen name.");
      }
      
  3. Cache Invalidation

    • Manually clear cache when needed:
      $cache->clear();
      

Extension Points

  1. Customize Tweet Parsing

    • Extend the TwitterClient class to transform raw tweet objects:
      class CustomTwitterClient extends TwitterClient {
          public function fetch($limit, $offset = 0) {
              $tweets = parent::fetch($limit, $offset);
              return array_map(function ($tweet) {
                  return [
                      'id' => $tweet->id,
                      'text' => $this->cleanText($tweet->text),
                      'url' => "https://twitter.com/{$tweet->user->screen_name}/status/{$tweet->id}"
                  ];
              }, $tweets);
          }
      
          private function cleanText($text) {
              // Remove URLs, mentions, etc.
              return preg_replace('/https?:\/\/[^\s]+/', '', $text);
          }
      }
      
  2. Add Rate Limiting

    • Implement a decorator to limit fetch frequency:
      class RateLimitedTwitterClient {
          private $client;
          private $lastFetch = 0;
          private $interval = 60; // 1 minute
      
          public function __construct(TwitterClient $client) {
              $this->client = $client;
          }
      
          public function fetch($limit) {
              if (time() - $this->lastFetch < $this->interval) {
                  throw new \RuntimeException("Rate limit exceeded. Try again later.");
              }
              $this->lastFetch = time();
              return $this->client->fetch($limit);
          }
      }
      
  3. Support Multiple Accounts

    • Create a factory to manage multiple clients:
      class TwitterClientFactory {
          public static function create($screenName, $cache = null) {
              $client = new TwitterClient($cache);
              $client->setScreenName($screenName);
              return $client;
          }
      }
      
      Usage:
      $client1 = TwitterClientFactory::create('laravel');
      $client2 = TwitterClientFactory::create('php');
      
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.
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
spatie/mailcoach-vapor