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

Seo Tool Bundle Laravel Package

daddl3/seo-tool-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation Add the bundle via Composer:

    composer require daddl3/seo-tool-bundle
    

    Enable the bundle in config/bundles.php:

    Daddl3\SeoToolBundle\Daddl3SeoToolBundle::class => ['all' => true],
    
  2. Basic Configuration Publish the default configuration:

    php bin/console daddl3:seo:install
    

    Update config/packages/daddl3_seo_tool.yaml to match your needs (e.g., canonical URLs, meta tags, OpenGraph defaults).

  3. First Use Case: Dynamic Meta Tags Use the SeoTool service in a controller to generate meta tags dynamically:

    use Daddl3\SeoToolBundle\Service\SeoTool;
    
    class PageController extends AbstractController
    {
        public function show(SeoTool $seoTool, $slug)
        {
            $seoTool->setTitle('My Page Title');
            $seoTool->setDescription('A dynamic description for my page.');
            $seoTool->setCanonicalUrl($this->generateUrl('page_show', ['slug' => $slug]));
    
            // Add OpenGraph tags
            $seoTool->setOpenGraph([
                'title' => 'OG Title',
                'description' => 'OG Description',
                'image' => $this->generateUrl('asset', {'path' => 'images/og-image.jpg'}),
            ]);
    
            return $this->render('page/show.html.twig');
        }
    }
    
  4. Twig Integration Ensure Twig is configured to render SEO tags. The bundle provides a seo Twig extension:

    {{ seo.render() }}
    

    Place this in your base template (e.g., base.html.twig) to auto-inject meta tags.


Implementation Patterns

Common Workflows

  1. Page-Specific SEO Override SEO settings per route or entity:

    // In a controller or event subscriber
    $seoTool->setTitle('Custom Title for ' ~ $entity->getName());
    $seoTool->setKeywords([$entity->getTagline(), 'related', 'tags']);
    
  2. Entity-Based SEO Use Doctrine listeners or Symfony’s PRE_PERSIST/PRE_UPDATE events to auto-generate SEO metadata from entities:

    // src/EventListener/SeoListener.php
    public function prePersist(PrePersistEventArgs $args)
    {
        $entity = $args->getObject();
        if ($entity instanceof SeoAwareInterface) {
            $seoTool->setTitle($entity->getSeoTitle());
            $seoTool->setDescription($entity->getSeoDescription());
        }
    }
    
  3. Dynamic Canonical URLs Generate canonical URLs based on route parameters:

    $seoTool->setCanonicalUrl(
        $this->generateUrl('product_show', ['id' => $product->getId(), 'slug' => $product->getSlug()])
    );
    
  4. Social Media Optimization Leverage OpenGraph/Twitter Cards for sharing:

    $seoTool->setOpenGraph([
        'type' => 'article',
        'url' => $this->generateUrl('article_show', ['id' => $article->getId()]),
        'images' => [$this->generateUrl('asset', {'path' => 'images/article.jpg'})],
    ]);
    $seoTool->setTwitterCard('summary_large_image');
    
  5. Conditional SEO Disable SEO tags for specific routes (e.g., admin pages):

    if ($this->isGranted('ROLE_ADMIN')) {
        $seoTool->disable();
    }
    

Integration Tips

  • Symfony Flex: The bundle follows Symfony Flex standards, so autoloading and configuration are handled automatically.
  • Twig Extensions: Use {{ seo.title }}, {{ seo.description }}, etc., in templates for granular control.
  • Event Dispatching: Extend functionality via events like seo.tool.build (fired before rendering).
  • Caching: Cache SEO metadata for static pages using Symfony’s cache system:
    $seoTool->setCache($cachePool->getItem('seo:page:' ~ $slug));
    

Gotchas and Tips

Pitfalls

  1. Configuration Overrides

    • The bundle merges configurations. Ensure your daddl3_seo_tool.yaml does not accidentally override defaults:
      # ❌ Bad: Overrides all OpenGraph tags globally
      daddl3_seo_tool:
          open_graph:
              title: "Default Title"  # Forces this on all pages
      
      # ✅ Good: Use `setOpenGraph` in controllers for dynamic values
      
  2. Twig Auto-Rendering

    • The {{ seo.render() }} tag must be placed in the <head> section of your template. Placing it elsewhere (e.g., <body>) will break rendering.
  3. Canonical URL Conflicts

    • If multiple routes generate the same canonical URL, search engines may penalize for duplicate content. Validate URLs in controllers:
      $canonicalUrl = $seoTool->getCanonicalUrl();
      if (strpos($canonicalUrl, '?') !== false) {
          throw new \RuntimeException('Canonical URL must not include query parameters.');
      }
      
  4. Entity Listeners and Circular References

    • Avoid circular references in Doctrine listeners (e.g., SeoAwareInterface triggering SEO updates recursively). Use @ORM\HasLifecycleCallbacks sparingly.
  5. Missing Assets

    • If OpenGraph/Twitter images are 404, the bundle will render broken links. Always validate asset paths:
      $imageUrl = $this->generateUrl('asset', {'path' => 'images/og-image.jpg'});
      if (!$this->isPathValid($imageUrl)) {
          $seoTool->setOpenGraphImage($this->generateUrl('asset', {'path' => 'images/default-og.jpg'}));
      }
      

Debugging Tips

  1. Enable Debug Mode Set debug: true in daddl3_seo_tool.yaml to log SEO metadata to the Symfony profiler:

    daddl3_seo_tool:
        debug: true
    

    Access via Profiler > SEO Tool.

  2. Validate HTML Output Use tools like Google’s Rich Results Test to validate OpenGraph/Twitter Cards.

  3. Check for Deprecated Methods The bundle may evolve. Refer to the CHANGELOG for breaking changes.

Extension Points

  1. Custom Tag Support Extend the bundle to add custom meta tags (e.g., article:published_time):

    // src/Service/SeoToolExtension.php
    public function addCustomTags(SeoTool $seoTool, array $tags)
    {
        foreach ($tags as $name => $content) {
            $seoTool->addMetaTag($name, $content);
        }
    }
    
  2. Event Subscribers Listen to seo.tool.build to modify metadata dynamically:

    // src/EventSubscriber/SeoSubscriber.php
    public function onSeoBuild(SeoBuildEvent $event)
    {
        $event->getSeoTool()->setKeywords(['custom', 'keywords']);
    }
    

    Register in services.yaml:

    services:
        App\EventSubscriber\SeoSubscriber:
            tags: ['kernel.event_subscriber']
    
  3. Custom Twig Functions Add helper functions to Twig for SEO-specific logic:

    // src/Twig/SeoExtension.php
    public function getSeoTitle(SeoTool $seoTool, string $fallback = null)
    {
        return $seoTool->getTitle() ?: $fallback;
    }
    

    Register in services.yaml:

    services:
        App\Twig\SeoExtension:
            tags: ['twig.extension']
    
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.
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
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver