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

dlapps/sitemap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Sitemap

  1. Installation

    composer require dlapps/sitemap-bundle
    

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

    DL\SitemapBundle\DLSitemapBundle::class => ['all' => true],
    
  2. First Sitemap Definition Create a service or command to define and generate a sitemap:

    use DL\SitemapBundle\Definition\Sitemap;
    use DL\SitemapBundle\Definition\Resource;
    
    $sitemap = new Sitemap();
    $sitemap->addResource(new Resource('https://example.com', '2023-10-01', 0.8, 'daily'));
    
  3. Generate and Output Use the SitemapGenerator service to render the sitemap:

    $generator = $container->get('dl_sitemap.generator');
    $xml = $generator->generate($sitemap);
    file_put_contents('public/sitemap.xml', $xml);
    
  4. First Use Case Generate a basic sitemap for your homepage and key routes:

    $sitemap = new Sitemap();
    $sitemap->addResource(new Resource('https://example.com'));
    $sitemap->addResource(new Resource('https://example.com/about'));
    $sitemap->addResource(new Resource('https://example.com/contact'));
    

Implementation Patterns

Common Workflows

  1. Dynamic Sitemap Generation Fetch routes dynamically from Symfony’s router and populate the sitemap:

    $router = $container->get('router');
    $routes = $router->getRouteCollection()->all();
    
    foreach ($routes as $route) {
        $sitemap->addResource(new Resource($router->generate($route->getName())));
    }
    
  2. Cron-Based Generation Schedule a command to regenerate sitemaps nightly (e.g., via cron or Laravel’s task scheduler):

    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class GenerateSitemapCommand extends Command
    {
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $sitemap = new Sitemap();
            // Add resources...
            $generator = $this->getContainer()->get('dl_sitemap.generator');
            file_put_contents('public/sitemap.xml', $generator->generate($sitemap));
            $output->writeln('Sitemap generated!');
        }
    }
    
  3. Multi-Language Sitemaps Use the Sitemap class to create separate sitemaps for each locale:

    $locales = ['en', 'fr', 'es'];
    foreach ($locales as $locale) {
        $sitemap = new Sitemap();
        $sitemap->setLocale($locale);
        // Add locale-specific resources...
        $generator->generate($sitemap, "public/sitemap_$locale.xml");
    }
    
  4. Integration with Controllers Generate sitemaps on-demand (e.g., for API-driven sites):

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    
    class SitemapController
    {
        #[Route('/sitemap.xml', name: 'sitemap')]
        public function generateSitemap(Request $request)
        {
            $sitemap = new Sitemap();
            // Add resources...
            $generator = $this->get('dl_sitemap.generator');
            return new Response($generator->generate($sitemap), 200, [
                'Content-Type' => 'application/xml',
            ]);
        }
    }
    

Integration Tips

  • Cache Sitemaps: Use Symfony’s cache system to store generated sitemaps and avoid regenerating them unnecessarily:
    $cache = $container->get('cache.app');
    if (!$cache->has('sitemap')) {
        $xml = $generator->generate($sitemap);
        $cache->set('sitemap', $xml, 3600); // Cache for 1 hour
    } else {
        $xml = $cache->get('sitemap');
    }
    
  • Extend Resource Class: Override the Resource class to add custom metadata (e.g., video sitemaps):
    class VideoResource extends Resource
    {
        public function __construct(string $loc, string $lastmod = null, float $changefreq = 0.5, string $priority = 1.0, string $title = null, string $description = null)
        {
            parent::__construct($loc, $lastmod, $changefreq, $priority);
            $this->title = $title;
            $this->description = $description;
        }
    }
    
  • Validation: Validate URLs before adding them to the sitemap to avoid broken links:
    use Symfony\Component\Validator\Validator\ValidatorInterface;
    
    $validator = $container->get('validator');
    $errors = $validator->validate($resource->getLoc(), new UrlConstraints());
    if (count($errors) === 0) {
        $sitemap->addResource($resource);
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony 3.x Usage

    • The bundle is designed for Symfony 3.2+, but Symfony 4+ requires adjustments (e.g., config/bundles.php instead of AppKernel.php). Ensure you’re using the correct registration method.
    • Fix: Update the bundle registration to use config/bundles.php for Symfony 4+:
      return [
          // ...
          DL\SitemapBundle\DLSitemapBundle::class => ['all' => true],
      ];
      
  2. XML Output Formatting

    • The generated XML may not always match Google’s sitemap specifications (e.g., missing ns namespace or incorrect root element). The bundle’s default output is minimal.
    • Fix: Customize the generator’s XML template or post-process the output:
      $xml = str_replace('<urlset>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', $xml);
      
  3. Large Sitemaps

    • Sitemaps exceeding 50MB or 50,000 URLs must be split into multiple files. The bundle does not handle this automatically.
    • Fix: Implement logic to split resources into chunks:
      $resources = $sitemap->getResources();
      $chunkSize = 50000;
      $chunks = array_chunk($resources, $chunkSize);
      
      foreach ($chunks as $index => $chunk) {
          $chunkSitemap = new Sitemap();
          foreach ($chunk as $resource) {
              $chunkSitemap->addResource($resource);
          }
          file_put_contents("public/sitemap_$index.xml", $generator->generate($chunkSitemap));
      }
      
  4. Lastmod Precision

    • The lastmod field should be in YYYY-MM-DD format. Using timestamps or incorrect formats may cause validation errors.
    • Fix: Ensure dates are formatted correctly:
      $resource = new Resource('https://example.com', (new \DateTime())->format('Y-m-d'));
      
  5. Dependency Conflicts

    • The bundle may conflict with other sitemap-related packages (e.g., spatie/sitemap). Avoid installing multiple sitemap packages in the same project.
    • Fix: Remove conflicting packages or refactor to use a single sitemap solution.

Debugging

  1. Validate XML Output Use online tools like XML Validation to check the generated sitemap for errors. Common issues include:

    • Missing url elements.
    • Incorrect namespace (xmlns).
    • Malformed URLs.
  2. Check Resource Order The bundle does not enforce any order for resources. If your sitemap requires a specific order (e.g., by priority), sort the resources manually:

    usort($sitemap->getResources(), function ($a, $b) {
        return $b->getPriority() <=> $a->getPriority();
    });
    
  3. Symfony Debug Mode Enable Symfony’s debug mode to catch issues early:

    APP_DEBUG=1 php bin/console dl:sitemap:generate
    

Extension Points

  1. Custom Generators Extend the SitemapGenerator to add custom logic (e.g., compression, signing):
    use DL\SitemapBundle\Generator\SitemapGenerator;
    
    class CustomSitemapGenerator extends SitemapGenerator
    {
        public function generate(Sitemap $s
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment