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

Xml Sitemap Bundle Laravel Package

dpn/xml-sitemap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dpn/xml-sitemap-bundle
    

    Enable the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):

    Dpn\XmlSitemapBundle\DpnXmlSitemapBundle::class => ['all' => true],
    
  2. Configure Routes: Add the sitemap route to your routes.yaml (Symfony 4+) or routing.yml:

    dpn_xml_sitemap:
        resource: "@DpnXmlSitemapBundle/Resources/config/routing.xml.yml"
        prefix: /
    
  3. First Use Case: Visit /sitemap.xml in your browser or via a crawler. The bundle auto-discovers routes annotated with @Route and generates a sitemap from them.


Key Configuration

Edit config/packages/dpn_xml_sitemap.yaml (Symfony 4+) or app/config/config.yml:

dpn_xml_sitemap:
    default_locale: en  # Fallback locale for routes without locale prefixes
    priority: 0.8       # Default priority for routes
    changefreq: weekly  # Default change frequency
    exclude_paths:      # Regex patterns to exclude routes
        - /admin/
        - /api/

Implementation Patterns

1. Route-Based Sitemap Generation

  • Auto-Discovery: The bundle scans all routes with @Route annotations. Prioritize routes with:

    /**
     * @Route("/products/{slug}", name="product_show", defaults={"priority"=0.9, "changefreq"="daily"})
     */
    public function show(Product $product) { ... }
    

    Override defaults via defaults in @Route.

  • Excluding Routes: Use exclude_paths in config or annotate routes:

    /**
     * @Route("/login", name="login", exclude_from_sitemap=true)
     */
    

2. Custom Generators

Extend functionality with custom generators (e.g., for dynamic content like blog posts).

Step 1: Create a generator class:

use Dpn\XmlSitemapBundle\Generator\GeneratorInterface;

class BlogPostGenerator implements GeneratorInterface
{
    public function generate(array $options)
    {
        $posts = Post::all(); // Fetch from DB
        return array_map(function ($post) {
            return [
                'loc' => route('post_show', $post),
                'lastmod' => $post->updated_at->format('Y-m-d'),
                'changefreq' => 'weekly',
                'priority' => 0.7,
            ];
        }, $posts->toArray());
    }
}

Step 2: Register the generator in config:

dpn_xml_sitemap:
    generators:
        blog_posts:
            class: App\Generator\BlogPostGenerator
            options:
                limit: 50  # Optional: Pass to generator

Step 3: Reference in routing:

dpn_xml_sitemap.blog_posts:
    path: /blog-sitemap.xml

3. Multi-Language Support

For locale-aware routes (e.g., /en/products, /fr/products):

dpn_xml_sitemap:
    default_locale: en
    locales:
        - en
        - fr

Ensure routes use _locale routing parameter:

/**
 * @Route("/products/{slug}", name="product_show", requirements={"_locale"="en|fr"})
 */

4. Dynamic Sitemap Updates

Trigger sitemap regeneration via console:

php bin/console dpn:xml-sitemap:generate

Or manually in a controller:

use Dpn\XmlSitemapBundle\Command\GenerateCommand;

public function regenerateSitemap()
{
    $command = new GenerateCommand();
    $command->run(new ArrayInput([]), new NullOutput());
}

5. Integration with Cron Jobs

Add a cron entry to regenerate sitemaps nightly (e.g., for dynamic content):

0 3 * * * cd /path/to/project && php bin/console dpn:xml-sitemap:generate --env=prod

Gotchas and Tips

Pitfalls

  1. Route Exclusion Overrides:

    • exclude_from_sitemap=true in @Route takes precedence over exclude_paths in config.
    • Test exclusions by checking the generated XML for unintended routes.
  2. Locale Mismatches:

    • If routes lack _locale, the default_locale is used. Ensure all routes are locale-aware or configure default_locale correctly.
  3. Performance with Large Route Sets:

    • Generating sitemaps for thousands of routes can be slow. Use exclude_paths to filter aggressively or implement custom generators for dynamic data.
  4. Caching Issues:

    • The bundle caches sitemaps by default. Clear cache after changes:
      php bin/console cache:clear
      php bin/console dpn:xml-sitemap:generate
      
  5. Deprecated Symfony Features:

    • The bundle is last updated for Symfony 3. The AppKernel registration step may fail in Symfony 4+. Use config/bundles.php instead.

Debugging Tips

  1. Inspect Generated XML:

    curl -s http://your-site.com/sitemap.xml | xmllint --format -
    

    Look for missing/duplicate URLs or incorrect priorities.

  2. Log Route Discovery: Enable debug mode and check logs for skipped routes:

    monolog:
        handlers:
            main:
                level: debug
    
  3. Validate Against Protocol: Use Google’s Sitemap Tester to catch malformed entries.


Extension Points

  1. Custom XML Output: Extend Dpn\XmlSitemapBundle\Generator\XmlGenerator to modify the XML structure (e.g., add <image:loc> tags for image sitemaps).

  2. Database-Backed Generators: For large datasets, implement GeneratorInterface with pagination:

    public function generate(array $options)
    {
        $page = $options['page'] ?? 1;
        $posts = Post::paginate(100, ['*'], 'page', $page);
        // Return paginated URLs
    }
    
  3. Event Listeners: Hook into dpn_xml_sitemap.generate event to modify URLs dynamically:

    use Dpn\XmlSitemapBundle\Event\GenerateEvent;
    
    public function onGenerate(GenerateEvent $event)
    {
        $urls = $event->getUrls();
        foreach ($urls as &$url) {
            $url['loc'] = str_replace('http://', 'https://', $url['loc']);
        }
    }
    

    Register in services.yaml:

    services:
        App\EventListener\SitemapListener:
            tags:
                - { name: kernel.event_listener, event: dpn_xml_sitemap.generate, method: onGenerate }
    

Configuration Quirks

  1. Priority/Changefreq Validation: The bundle validates priority (0.0–1.0) and changefreq (always, hourly, daily, weekly, monthly, yearly, never). Invalid values default to config defaults.

  2. Lastmod Handling:

    • If no lastmod is provided, the bundle uses the current timestamp.
    • For dynamic content, ensure your generator includes accurate lastmod values.
  3. Index Sitemaps: To create a sitemap index (for large sites), use multiple routes:

    dpn_xml_sitemap.main:
        path: /sitemap.xml
    dpn_xml_sitemap.blog:
        path: /sitemap-blog.xml
    

    Then manually create an index file or use a custom generator to aggregate URLs.

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