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

Rss Client Bundle Laravel Package

desarrolla2/rss-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require desarrolla2/rss-client-bundle
    

    Register the bundle in app/Kernel.php:

    new Desarrolla2\Bundle\RSSClientBundle\RSSClientBundle(),
    
  2. Basic Configuration: Add RSS channels in config/packages/rss_client.yaml (or config.yml for older Laravel versions):

    rss_client:
        channels:
            news:
                - 'https://example.com/rss-feed'
                - 'https://example.com/another-feed'
        cache:
            ttl: 3600  # Cache TTL in seconds (default: 3600)
    
  3. First Use Case: Fetch and display RSS items in a controller:

    use Desarrolla2\Bundle\RSSClientBundle\Service\RSSClient;
    
    public function index(RSSClient $rssClient)
    {
        $items = $rssClient->getItems('news'); // 'news' is the channel name
        return view('rss.items', compact('items'));
    }
    

Implementation Patterns

Common Workflows

  1. Fetching and Displaying Feeds:

    • Use dependency injection to access the RSSClient service in controllers or services.
    • Example: Fetch and display the latest 5 items from a channel:
      $items = $rssClient->getItems('news', 5);
      
  2. Customizing Item Processing:

    • Extend the default behavior by creating a custom service that implements Desarrolla2\Bundle\RSSClientBundle\Service\RSSItemInterface.
    • Example:
      class CustomRSSItem extends AbstractRSSItem
      {
          public function getTitle(): string
          {
              return '[Custom] ' . parent::getTitle();
          }
      }
      
    • Register the custom service in services.yaml:
      servicios.rss_item:
          class: App\Service\CustomRSSItem
          tags: ['rss_client.item']
      
  3. Caching Strategies:

    • Leverage the built-in caching (default: 1 hour) to reduce external API calls.
    • Clear cache manually if needed:
      $rssClient->clearCache('news');
      
  4. Handling Multiple Channels:

    • Group related feeds under a single channel name (e.g., news, tech) for easier management.
    • Example configuration:
      rss_client:
          channels:
              tech_news:
                  - 'https://tech-site.com/rss'
                  - 'https://another-tech-site.com/feed'
      
  5. Integration with Twig:

    • Pass RSS items directly to Twig templates:
      return view('rss.index', [
          'newsItems' => $rssClient->getItems('news'),
          'techItems' => $rssClient->getItems('tech_news'),
      ]);
      
    • Use Twig loops to iterate over items:
      {% for item in newsItems %}
          <h3>{{ item.title }}</h3>
          <p>{{ item.description|truncate(100) }}</p>
      {% endfor %}
      
  6. Scheduled Fetching:

    • Use Laravel's task scheduling to fetch RSS feeds periodically (e.g., every 6 hours):
      // app/Console/Kernel.php
      protected function schedule(Schedule $schedule)
      {
          $schedule->call(function () {
              $rssClient = app('rss_client');
              $rssClient->fetchAllChannels();
          })->hourly();
      }
      

Gotchas and Tips

Pitfalls and Debugging

  1. Feed Parsing Errors:

    • Invalid RSS feeds may throw exceptions. Wrap calls in try-catch blocks:
      try {
          $items = $rssClient->getItems('news');
      } catch (\Exception $e) {
          Log::error('RSS fetch failed: ' . $e->getMessage());
          $items = []; // Fallback to empty array
      }
      
  2. Caching Issues:

    • If feeds aren’t updating, clear the cache manually:
      php bin/console cache:clear
      
    • Or programmatically:
      $rssClient->clearCache(); // Clears all channels
      $rssClient->clearCache('news'); // Clears a specific channel
      
  3. Channel Configuration:

    • Ensure channel names in config.yml match those used in code (case-sensitive).
    • Avoid special characters in channel names (e.g., tech-news instead of tech/news).
  4. Rate Limiting:

    • Some RSS providers may block frequent requests. Adjust the cache TTL (ttl) to avoid hitting limits:
      rss_client:
          cache:
              ttl: 10800  # 3 hours
      
  5. SSL/TLS Issues:

    • If fetching HTTPS feeds fails, ensure your server has valid SSL certificates or configure cURL to ignore SSL errors (not recommended for production):
      $client = new \GuzzleHttp\Client([
          'curl' => [
              CURLOPT_SSL_VERIFYPEER => false,
          ],
      ]);
      // Inject the client into the bundle (requires customization)
      
  6. Large Feeds:

    • Feeds with thousands of items may cause performance issues. Limit the number of items fetched:
      $items = $rssClient->getItems('news', 10); // Fetch only 10 items
      

Tips and Tricks

  1. Custom Item Fields:

    • Extend the AbstractRSSItem class to add custom fields (e.g., getAuthor(), getImageUrl()):
      class ExtendedRSSItem extends AbstractRSSItem
      {
          public function getAuthor(): ?string
          {
              return $this->getElement('author') ?? null;
          }
      }
      
  2. Logging:

    • Enable logging to debug feed fetching:
      rss_client:
          logging: true
      
    • Check logs in storage/logs/laravel.log.
  3. Testing:

    • Mock the RSSClient service in tests:
      $this->mock(RSSClient::class)
           ->shouldReceive('getItems')
           ->with('news')
           ->andReturn([/* mock items */]);
      
  4. Performance Optimization:

    • Use Laravel's queue system to fetch feeds asynchronously:
      FetchRSSFeedsJob::dispatch('news')->onQueue('rss');
      
    • Create a job:
      class FetchRSSFeedsJob implements ShouldQueue
      {
          use Dispatchable, InteractsWithQueue, Queueable;
      
          public function handle(RSSClient $rssClient)
          {
              $rssClient->fetchChannel($this->channelName);
          }
      }
      
  5. Dynamic Channel Configuration:

    • Load channel configurations dynamically (e.g., from a database) by extending the bundle or overriding the ChannelManager service.
  6. Handling Different RSS Formats:

    • The bundle supports standard RSS/Atom formats. For custom formats, extend the RSSClient class and override the parseFeed method.
  7. Security:

    • Sanitize RSS content before displaying it to users to prevent XSS:
      use Symfony\Component\DomCrawler\Crawler;
      $cleanedDescription = (new Crawler($item->getDescription()))->text();
      
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php