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

Feed Builder Laravel Package

anh/feed-builder

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require anh/feed-builder:~1.0
    

    Add to composer.json under require if not using global install.

  2. First Use Case: Generate a basic RSS/Atom feed from an array:

    use Anh\FeedBuilder\FeedBuilder;
    
    $feed = (new FeedBuilder())
        ->setType('atom') // or 'rss'
        ->fromArray([
            'title' => 'My Blog',
            'link' => ['href' => url('/feed')],
            'entry-1' => [
                'title' => 'First Post',
                'link' => url('/post/1'),
            ],
        ]);
    echo $feed; // Outputs XML
    
  3. Key Files:

    • vendor/anh/feed-builder/src/ for core logic.
    • Focus on FeedBuilder.php for API reference.

Implementation Patterns

Core Workflows

  1. Data-Driven Feed Generation: Use fromArray() for structured data (e.g., Eloquent collections):

    $posts = Post::all()->map(fn($p) => [
        'title' => $p->title,
        'link' => url("/posts/{$p->id}"),
        'id' => $p->slug,
        'content' => $p->body,
    ]);
    $feed->fromArray([
        'title' => 'Blog Feed',
        ...$posts->pluck('title', 'link', 'id', 'content')->toArray(),
    ]);
    
  2. Dynamic Entry Handling: Loop through models/collections to build entries:

    foreach ($posts as $index => $post) {
        $feed->addEntry([
            'title' => $post->title,
            'link' => url("/posts/{$post->id}"),
            'id' => "tag:{$post->id},{$post->created_at->timestamp}",
        ]);
    }
    
  3. Validation Integration: Validate before output:

    if (!$feed->validate()) {
        Log::error('Feed validation failed', ['errors' => $feed->getErrors()]);
        abort(500, 'Invalid feed generated');
    }
    

Laravel-Specific Patterns

  1. Service Provider Binding: Bind FeedBuilder in AppServiceProvider:

    $this->app->bind(FeedBuilder::class, function ($app) {
        return new FeedBuilder(config('feed.type', 'atom'));
    });
    
  2. Route Integration:

    Route::get('/feed', function () {
        $feed = app(FeedBuilder::class)
            ->setType(config('feed.type'))
            ->fromArray($this->getFeedData());
        return response($feed, 200, ['Content-Type' => 'application/xml']);
    });
    
  3. Configuration: Use config/feed.php to centralize settings:

    return [
        'type' => env('FEED_TYPE', 'atom'),
        'default_title' => 'My Site Feed',
        'default_link' => '/',
    ];
    

Gotchas and Tips

Pitfalls

  1. Validation Incompleteness:

    • The validator is "not fully completed" (per README). Test feeds manually or use external validators (e.g., W3C Feed Validation).
    • Workaround: Use try-catch for validate():
      try {
          $feed->validate();
      } catch (\Exception $e) {
          // Fallback to external validation
      }
      
  2. Date Formatting:

    • Relative dates (e.g., 'tomorrow') may fail validation. Use ISO 8601:
      'updated' => now()->toAtomString(), // Atom
      'pubDate' => now()->toRfc822String(), // RSS
      
  3. Entry Naming:

    • RSS requires item keys (e.g., item-1, item2), while Atom uses entry-*. Mixing formats breaks feeds.
    • Fix: Standardize keys or use addEntry() for clarity.
  4. HTML Content:

    • Atom requires <content> to specify type (e.g., html or xhtml). Omitting it defaults to text:
      'content' => [
          'type' => 'html',
          '<div>Safe HTML</div>',
      ],
      

Debugging Tips

  1. Inspect Raw XML:

    $xml = $feed->getXml();
    file_put_contents(storage_path('logs/feed.xml'), $xml);
    
  2. Error Handling:

    • Check $feed->getErrors() for validation failures.
    • Log raw input arrays to debug mismatches:
      Log::debug('Feed input', ['data' => $feed->getData()]);
      

Extension Points

  1. Custom Validators: Extend Anh\FeedBuilder\Validator\ValidatorInterface for domain-specific rules.

  2. Template Overrides: Override XML templates in vendor/anh/feed-builder/src/Resources/views/ by publishing assets:

    php artisan vendor:publish --tag=feed-builder-views
    
  3. Caching: Cache generated feeds (e.g., with Cache::remember):

    return Cache::remember('feed_xml', now()->addHours(1), function () {
        return app(FeedBuilder::class)->fromArray($data);
    });
    

Pro Tips

  • Use addEntry() for Dynamic Entries: Avoid array key collisions with programmatic entries:

    $feed->addEntry(['title' => 'Dynamic Post', 'link' => url('/dynamic')]);
    
  • Leverage Laravel Collections: Transform collections directly:

    $feed->fromArray($posts->map->toArray());
    
  • Test with Real Data: Validate against FeedValidator.org for edge cases.

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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle