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

Sitemap Bundle Laravel Package

ekyna/sitemap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer (note: package is outdated; verify compatibility with Laravel 5.5+ via custom fork or wrapper):

    composer require ekyna/sitemap-bundle
    

    Register the bundle in config/app.php (Symfony-specific; for Laravel, use a service provider wrapper or manual integration).

  2. First Use Case Generate a basic sitemap for your routes:

    // In a controller or command
    $sitemap = $this->get('ekyna_sitemap.sitemap_generator')->generate();
    $sitemap->addUrl('http://example.com', ['priority' => 1.0, 'changefreq' => 'daily']);
    $sitemap->render('xml'); // Outputs XML to response
    
  3. Where to Look First

    • Documentation: Check the GitHub README (though incomplete).
    • Source: Review SitemapGenerator class for core logic (e.g., addUrl(), render()).
    • Symfony Integration: Study DependencyInjection for service configuration (adapt for Laravel’s container).

Implementation Patterns

Core Workflows

  1. Dynamic Sitemap Generation

    • Route-Based: Loop through Laravel’s routes and auto-generate URLs:
      foreach (Route::getRoutes()->getRoutes() as $route) {
          $sitemap->addUrl(url($route->uri()), [
              'priority' => $route->priority ?? 0.8,
              'changefreq' => 'weekly'
          ]);
      }
      
    • Model-Based: Fetch active records and map to URLs:
      Post::where('published', true)->each(function ($post) use ($sitemap) {
          $sitemap->addUrl(route('post.show', $post), ['priority' => 0.9]);
      });
      
  2. Caching

    • Cache generated sitemaps to avoid regeneration on every request:
      $cachedSitemap = Cache::remember('sitemap_xml', now()->addHours(1), function () {
          return $this->generateSitemap();
      });
      
  3. Multi-Language Support

    • Use route parameters to generate locale-specific sitemaps:
      $sitemap->addUrl(route('post.show', ['post' => $post, 'locale' => 'fr']));
      
  4. Integration with Laravel

    • Middleware: Add sitemap generation to a middleware for automatic inclusion:
      public function handle($request, Closure $next) {
          if ($request->is('sitemap.xml')) {
              return $this->generateSitemap();
          }
          return $next($request);
      }
      
    • Commands: Schedule sitemap regeneration via Artisan:
      Artisan::command('sitemap:generate', function () {
          $this->generateSitemap()->save(public_path('sitemap.xml'));
      });
      
  5. Image/Video Sitemaps

    • Extend the bundle to support media-specific sitemaps (e.g., addImageUrl()):
      $sitemap->addMediaUrl('http://example.com/image.jpg', [
          'loc' => 'http://example.com',
          'title' => 'Example Image',
          'caption' => 'Description'
      ]);
      

Gotchas and Tips

Pitfalls

  1. Outdated Package

    • Issue: Last release in 2015; may not support Laravel’s latest features (e.g., route caching, container changes).
    • Workaround:
      • Fork the repository and update dependencies (e.g., replace Symfony components with Laravel equivalents).
      • Use a wrapper class to abstract the bundle’s functionality:
        class LaravelSitemapService {
            public function generate() {
                $generator = new \Ekyna\SitemapBundle\SitemapGenerator();
                // Adapt methods to Laravel conventions
                return $generator;
            }
        }
        
  2. XML Namespaces

    • Issue: Bundle may not include required XML namespaces for image/video sitemaps.
    • Fix: Manually append namespaces to the XML output:
      $xml = $sitemap->render('xml');
      $xml = str_replace('<urlset>', '<urlset xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">', $xml);
      
  3. URL Normalization

    • Issue: Bundle may not handle URL normalization (e.g., trailing slashes, HTTPS).
    • Tip: Pre-process URLs before adding them:
      $url = str_replace(['http://', 'https://'], '', $url);
      $sitemap->addUrl(url($url));
      
  4. Performance

    • Issue: Generating large sitemaps (>50,000 URLs) may cause memory/timeouts.
    • Tip:
      • Split sitemaps into multiple files (e.g., sitemap1.xml, sitemap2.xml).
      • Use chunking for database queries:
        Post::query()->chunk(1000, function ($posts) use ($sitemap) {
            foreach ($posts as $post) {
                $sitemap->addUrl(route('post.show', $post));
            }
        });
        
  5. Testing

    • Issue: No built-in testing utilities.
    • Tip: Mock the SitemapGenerator in PHPUnit:
      $mockSitemap = $this->getMockBuilder(\Ekyna\SitemapBundle\SitemapGenerator::class)
          ->onlyMethods(['render'])
          ->getMock();
      $mockSitemap->expects($this->once())->method('render')->willReturn('<urlset>...</urlset>');
      

Debugging

  • Log Output: Enable debug mode to log generated XML:
    $xml = $sitemap->render('xml');
    Log::debug('Sitemap XML:', ['xml' => $xml]);
    
  • Validate XML: Use online tools (e.g., XML Validation) to check for errors.

Extension Points

  1. Custom URL Providers

    • Implement a service to dynamically fetch URLs:
      class DynamicUrlProvider {
          public function getUrls() {
              return [
                  ['url' => '/dynamic-page', 'priority' => 0.7],
                  // ...
              ];
          }
      }
      
  2. Post-Processing

    • Hook into the render() method to modify XML:
      $xml = $sitemap->render('xml');
      $xml = $this->postProcessXml($xml); // Add custom logic
      
  3. Storage Backends

    • Extend to support database storage or cloud storage (e.g., S3):
      $sitemap->saveToStorage(new S3SitemapStorage());
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware