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

presta/sitemap-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require presta/sitemap-bundle

Enable the bundle in config/bundles.php:

return [
    // ...
    Presta\SitemapBundle\PrestaSitemapBundle::class => ['all' => true],
];
  1. Basic Configuration Add to config/packages/presta_sitemap.yaml:

    presta_sitemap:
        default_locale: en
        base_url: 'https://yourdomain.com'
        sitemap:
            filename: 'sitemap.xml'
            format: 'xml'
    
  2. First Use Case: Static Sitemap Create a controller to generate and serve the sitemap:

    use Presta\SitemapBundle\Generator\SitemapGenerator;
    use Symfony\Component\HttpFoundation\Response;
    
    class SitemapController
    {
        public function generate(SitemapGenerator $generator): Response
        {
            $sitemap = $generator->generate();
            return new Response($sitemap, 200, ['Content-Type' => 'application/xml']);
        }
    }
    

    Route it in config/routes.yaml:

    sitemap:
        path: /sitemap.xml
        controller: App\Controller\SitemapController::generate
    
  3. Documentation Start with the official docs and focus on:

    • Generator\SitemapGenerator class
    • Model\Sitemap and Model\SitemapUrl entities
    • Twig integration (if using templates)

Implementation Patterns

Core Workflow: Dynamic Sitemap Generation

  1. Define Sitemap URLs Use the SitemapUrl model to define URLs dynamically:

    use Presta\SitemapBundle\Model\SitemapUrl;
    
    $url = new SitemapUrl();
    $url->setLoc('/blog/post-1');
    $url->setLastmod(new \DateTime());
    $url->setChangefreq('weekly');
    $url->setPriority(0.8);
    
  2. Register URLs with the Generator

    $generator = $this->get('presta.sitemap.generator');
    $generator->addUrl($url);
    
  3. Batch Processing for Large Sitemaps For sitemaps with >50,000 URLs, split into multiple files using SitemapIndexGenerator:

    $indexGenerator = $this->get('presta.sitemap.index_generator');
    $indexGenerator->addSitemap('sitemap_part1.xml', new \DateTime());
    $indexGenerator->addSitemap('sitemap_part2.xml', new \DateTime());
    

Integration Patterns

  1. Doctrine Entity Integration Use the SitemapUrlRepository to fetch URLs from a database:

    $urls = $this->get('presta.sitemap.url.repository')->findAll();
    foreach ($urls as $url) {
        $generator->addUrl($url);
    }
    
  2. Event-Driven Updates Trigger sitemap regeneration on entity events (e.g., PostUpdatedEvent):

    use Presta\SitemapBundle\Event\SitemapEvent;
    
    public function onPostUpdated(PostUpdatedEvent $event)
    {
        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->dispatch(new SitemapEvent('post.updated', $event->getPost()));
    }
    
  3. Twig Templates for Customization Override default templates in templates/PrestaSitemapBundle/:

    {# templates/PrestaSitemapBundle/Sitemap/sitemap.xml.twig #}
    <?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        {% for url in urls %}
            <url>
                <loc>{{ url.loc }}</loc>
                {% if url.lastmod %}<lastmod>{{ url.lastmod|date('c') }}</lastmod>{% endif %}
                {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
                {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
            </url>
        {% endfor %}
    </urlset>
    
  4. Caching for Performance Cache generated sitemaps using Symfony’s cache system:

    # config/packages/presta_sitemap.yaml
    presta_sitemap:
        cache:
            enabled: true
            lifetime: 3600  # 1 hour
    
  5. Multi-Language Support Generate locale-specific sitemaps:

    presta_sitemap:
        locales:
            en:
                filename: 'sitemap_en.xml'
            fr:
                filename: 'sitemap_fr.xml'
    

Gotchas and Tips

Common Pitfalls

  1. URL Encoding Issues

    • Ensure loc values are absolute URLs (include base_url from config).
    • Use UrlGeneratorInterface to generate correct paths:
      $url = $this->get('router')->generate('route_name', ['id' => 1], UrlGeneratorInterface::ABSOLUTE_URL);
      
  2. DateTime Formatting

    • lastmod must be in RFC 3339 format (YYYY-MM-DDTHH:MM:SS+HH:MM). Use:
      $url->setLastmod(new \DateTime('now', new \DateTimeZone('UTC')));
      
  3. XML Validation Errors

    • Validate against sitemap schema.
    • Common issues:
      • Missing xmlns namespace in sitemapindex.
      • Duplicate <loc> entries.
      • Invalid priority values (must be 0.01.0).
  4. Caching Headaches

    • Clear cache manually after changes:
      php bin/console cache:clear
      
    • Disable caching during development:
      presta_sitemap:
          cache:
              enabled: false
      
  5. Large Sitemap Performance

    • Avoid loading all URLs into memory at once. Use pagination or batch processing:
      $qb = $this->get('presta.sitemap.url.repository')->createQueryBuilder('u');
      $qb->setMaxResults(1000);
      $urls = $qb->getQuery()->getResult();
      

Debugging Tips

  1. Enable Verbose Logging

    presta_sitemap:
        debug: true
    

    Check logs for generated XML snippets.

  2. Validate XML Output Use an online validator like XML Validation or CLI:

    xmllint --noout --schema http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd sitemap.xml
    
  3. Check for Deprecated Methods

    • The bundle evolves; check the upgrade guide for breaking changes.

Extension Points

  1. Custom URL Providers Implement Presta\SitemapBundle\Provider\UrlProviderInterface:

    class CustomUrlProvider implements UrlProviderInterface
    {
        public function getUrls(): array
        {
            return [
                new SitemapUrl('/custom-path', new \DateTime()),
            ];
        }
    }
    

    Register as a service:

    services:
        App\Provider\CustomUrlProvider:
            tags:
                - { name: presta.sitemap.url_provider }
    
  2. Override Generators Extend SitemapGenerator or SitemapIndexGenerator:

    class CustomSitemapGenerator extends SitemapGenerator
    {
        protected function getTemplate(): string
        {
            return '@App/Sitemap/custom_sitemap.xml.twig';
        }
    }
    

    Replace the service in config/services.yaml:

    Presta\SitemapBundle\Generator\SitemapGenerator: '@App\Generator\CustomSitemapGenerator'
    
  3. Add Custom XML Attributes Extend SitemapUrl or use a custom model:

    class ExtendedSitemapUrl extends SitemapUrl
    {
        private $imageLoc;
    
        // Getters/setters...
    }
    

    Update the Twig template to include new fields.

  4. Integrate with API Platform

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui