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

Darvin Sitemap Bundle Laravel Package

darvinstudio/darvin-sitemap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    • Add the bundle to composer.json under "require":
      "darvinstudio/darvin-sitemap-bundle": "1.0.*"
      
    • Run composer update darvinstudio/darvin-sitemap-bundle.
    • Register the bundle in AppKernel.php:
      new Darvin\SitemapBundle\DarvinSitemapBundle(),
      
    • Import routing in app/config/routing.yml:
      darvin_sitemap:
          resource: "@DarvinSitemapBundle/Resources/config/routing.yml"
          prefix: /
      
  2. First Use Case:

    • Create a service implementing SitemapUrlProviderInterface to define URLs for your sitemap.
    • Example: Generate a basic sitemap with static URLs (e.g., homepage, blog posts, or product pages).
    • Access the sitemap at /sitemap.xml (default route).

Where to Look First

  • Bundle Documentation: Focus on the SitemapUrlProviderInterface and SitemapUrl classes in the src/Darvin/SitemapBundle/Url namespace.
  • Routing: Check DarvinSitemapBundle/Resources/config/routing.yml for the default route (/sitemap.xml).
  • Configuration: Review DarvinSitemapBundle/Resources/config/services.yml for default service definitions.

Implementation Patterns

Core Workflow

  1. Define Providers:

    • Implement SitemapUrlProviderInterface for each logical group of URLs (e.g., BlogSitemapProvider, ProductSitemapProvider).
    • Example:
      class BlogSitemapProvider implements SitemapUrlProviderInterface
      {
          public function getSitemapUrls()
          {
              return array_map(function ($post) {
                  return new SitemapUrl(
                      $this->generateUrl('post_show', ['slug' => $post->slug]),
                      $post->updatedAt,
                      'daily',
                      $post->priority
                  );
              }, $this->blogRepository->findAll());
          }
      }
      
  2. Tag Services:

    • Register each provider as a service and tag it with darvin_sitemap.url_provider:
      # app/config/services.yml
      services:
          app.sitemap.blog_provider:
              class: AppBundle\Sitemap\BlogSitemapProvider
              tags:
                  - { name: darvin_sitemap.url_provider }
      
  3. Dynamic URL Generation:

    • Use Symfony’s UrlGeneratorInterface to generate routes dynamically:
      $urlGenerator = $this->container->get('router');
      $url = $urlGenerator->generate('route_name', ['param' => 'value']);
      
  4. Sitemap Indexing:

    • For large sites, split URLs into multiple sitemaps (e.g., sitemap1.xml, sitemap2.xml) and reference them in a sitemap index (sitemap.xml).
    • Example provider for indexing:
      class SitemapIndexProvider implements SitemapUrlProviderInterface
      {
          public function getSitemapUrls()
          {
              return [
                  new SitemapUrl('/sitemap1.xml', new \DateTime(), 'always'),
                  new SitemapUrl('/sitemap2.xml', new \DateTime(), 'always'),
              ];
          }
      }
      
  5. Caching:

    • Cache generated sitemaps to avoid regenerating on every request. Use Symfony’s cache system:
      $cache = $this->container->get('cache.app');
      if (!$cache->has('sitemap_content')) {
          $content = $this->generateSitemap();
          $cache->set('sitemap_content', $content, 3600); // Cache for 1 hour
      }
      

Integration Tips

  • Doctrine Integration:

    • Fetch entities from repositories and map them to SitemapUrl objects. Example:
      $products = $this->productRepository->findBy([], ['createdAt' => 'DESC']);
      $urls = array_map(function ($product) {
          return new SitemapUrl(
              $this->generateUrl('product_show', ['id' => $product->id]),
              $product->updatedAt,
              'weekly',
              0.8
          );
      }, $products);
      
  • Translation:

    • Use Symfony’s translation system to localize sitemap URLs or metadata (e.g., <loc> tags for multilingual sites).
  • Testing:

    • Mock SitemapUrlProviderInterface in unit tests to verify URL generation logic:
      $provider = $this->createMock(SitemapUrlProviderInterface::class);
      $provider->method('getSitemapUrls')->willReturn([new SitemapUrl('test', new \DateTime())]);
      $this->container->set('app.sitemap.test_provider', $provider);
      

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony2:

    • The bundle is designed for Symfony 2.x (last release in 2016). Ensure compatibility with your Symfony 2.x version (e.g., 2.3–2.8). Avoid using with Symfony 3+ or 4+ without significant refactoring.
  2. Routing Conflicts:

    • The default route /sitemap.xml may conflict with existing routes. Override the route in your routing.yml:
      darvin_sitemap:
          resource: "@DarvinSitemapBundle/Resources/config/routing.yml"
          prefix: /custom-prefix
      
  3. XML Validation:

  4. Performance:

    • Generating sitemaps dynamically on every request can be slow for large sites. Always cache the output or use a cron job to pre-generate sitemaps.
  5. Service Tagging:

    • Forgetting to tag a provider with darvin_sitemap.url_provider will silently exclude it from the sitemap. Verify tags with:
      php bin/console debug:container --tag=darvin_sitemap.url_provider
      

Debugging

  1. Log Provider Output:

    • Temporarily log the URLs generated by each provider to debug missing or incorrect entries:
      $urls = $this->getSitemapUrls();
      foreach ($urls as $url) {
          $this->logger->info('Sitemap URL: ' . $url->getLoc());
      }
      
  2. Check Bundle Configuration:

    • Ensure the bundle is properly registered in AppKernel.php and routing is imported. Test with:
      php bin/console debug:router | grep sitemap
      
  3. Validate XML Output:

    • Inspect the raw XML response at /sitemap.xml for syntax errors. Use browser dev tools or curl:
      curl -v http://your-site.com/sitemap.xml
      

Tips

  1. Extend SitemapUrl:

    • Create custom properties or methods in a child class for domain-specific needs:
      class CustomSitemapUrl extends SitemapUrl
      {
          private $customData;
      
          public function __construct($loc, \DateTime $lastmod, $changefreq, $priority, $customData)
          {
              parent::__construct($loc, $lastmod, $changefreq, $priority);
              $this->customData = $customData;
          }
      
          public function getCustomData()
          {
              return $this->customData;
          }
      }
      
  2. Use Events:

    • Listen to the darvin_sitemap.generate event to modify the sitemap before rendering. Example in a subscriber:
      public function onSitemapGenerate(GetResponseEvent $event)
      {
          $sitemap = $event->getSitemap();
          $sitemap->addUrl(new SitemapUrl('http://example.com/extra-page'));
      }
      
  3. Custom Templates:

    • Override the default XML template by extending the bundle’s controller or twig template. Locate the template at: DarvinSitemapBundle/Resources/views/Sitemap/sitemap.xml.twig.
  4. Prioritize Critical Pages:

    • Assign higher priority (1.0) to key pages (e.g., homepage, checkout) and lower priority (0.1) to less critical content.
  5. Monitor Changes:

    • Use the changefreq parameter wisely:
      • always: Critical pages (e.g., homepage).
      • hourly: News or time-sensitive content.
      • daily: Blog posts or product pages.
      • weekly: Static pages like "About Us."
      • monthly: Archive pages.
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours