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 Bundle Laravel Package

ayrel/seo-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ayrel/seo-bundle
    

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

    Ayrel\SeoBundle\AyrelSeoBundle::class => ['all' => true],
    
  2. First Use Case: Add the @Seo annotation to a controller method to dynamically generate SEO tags:

    use Ayrel\SeoBundle\Annotation\SeoAnnotation;
    
    class PageController extends Controller
    {
        /**
         * @Route("/about", name="about")
         * @Seo({
         *     "title": "About Us | {{_route}}",
         *     "description": "Learn about our company"
         * })
         */
        public function aboutAction()
        {
            return $this->render('about.html.twig');
        }
    }
    
    • Key Variables: _route (route name), _controller (FQCN), and any ParamConverter entities (e.g., {{product.title}}).
  3. Verify Output: Inspect the rendered HTML to confirm <title> and <meta> tags are dynamically populated.


Implementation Patterns

1. Annotation-Based Configuration

  • Route-Specific SEO: Use @Seo annotations for granular control over individual routes. Example:
    @Seo({
        "title": "{{user.name}}'s Profile",
        "og:image": "{{asset('images/profile/' ~ user.avatar)}}"
    })
    
  • Fallback to Defaults: Set ~ (null) in annotations to inherit defaults from config.yml:
    # config/packages/ayrel_seo.yaml
    ayrel_seo:
        default:
            title: "My Site | {_route}"
            description: "Default description for all pages"
    

2. YAML Configuration for Bulk Routes

  • Centralize SEO rules in config/seo.yml:
    homepage:
        title: "Welcome to {{app.name}}"
        description: "Discover our services"
    blog_post:
        title: "{{post.title}} | {{app.name}}"
        description: "{{post.excerpt}}"
        og:title: "{{post.title}}"
    
  • Route Matching: The bundle matches routes by name (e.g., blog_post for /blog/{slug}).

3. Dynamic Data Injection

  • ParamConverter Integration: Access entity properties directly in Twig patterns:
    @Seo({
        "title": "{{product.name}} - Price: {{product.price}}€",
        "description": "{{product.shortDescription}}"
    })
    public function showAction(Product $product)
    
  • Request Attributes: Use _request to access query params or session data:
    search:
        title: "Results for '{{_request.query.search}}'"
    

4. Twig Integration

  • Custom Strategies: Extend the Twig renderer for complex logic (see Twig Strategy Docs). Example: Override Ayrel\SeoBundle\Twig\SeoTwigStrategy to add custom filters.

5. Open Graph & Social Tags

  • Define Open Graph (og:) and Twitter Card (twitter:) tags in the same config:
    product:
        og:title: "{{product.title}}"
        og:description: "{{product.description}}"
        og:image: "{{asset('images/' ~ product.image)}}"
        twitter:card: "summary_large_image"
    

6. Conditional Logic

  • Use Twig’s if in patterns (via {% if %} or {{ ... ? 'yes' : 'no' }}):
    article:
        title: "{{article.published ? article.title : 'Draft: ' ~ article.title}}"
    

Gotchas and Tips

Pitfalls

  1. Route Name Mismatches:

    • The bundle matches routes by name (e.g., homepage). Ensure @Route names in controllers match the YAML keys.
    • Fix: Use @Route(name="exact_match") explicitly.
  2. Circular References:

    • Avoid recursive Twig patterns (e.g., {{product.category.parent.name}} where parent is lazy-loaded).
    • Fix: Pre-load relationships or use {{ product.category ? product.category.name : 'Uncategorized' }}.
  3. Asset Paths in SEO Tags:

    • Hardcoding {{asset('image.jpg')}} may break if the asset pipeline changes.
    • Fix: Use absolute URLs or configure ayrel_seo.asset_base_url in config.yml.
  4. Annotation Parsing Issues:

    • Symfony’s annotation reader may fail if the @Seo annotation isn’t properly imported.
    • Fix: Ensure the use statement is at the top of the file:
      use Ayrel\SeoBundle\Annotation\SeoAnnotation as Seo;
      
  5. Caching Headaches:

    • SEO tags rendered via Twig may not update if the template cache is stale.
    • Fix: Clear the cache after changes:
      php bin/console cache:clear
      

Debugging Tips

  1. Inspect Request Attributes: Dump available variables in a controller to debug Twig patterns:

    public function debugAction(Request $request)
    {
        dd($request->attributes->all());
    }
    
  2. Override Twig Strategy: Create a custom strategy to log or modify SEO data:

    // src/Twig/SeoDebugStrategy.php
    class SeoDebugStrategy extends SeoTwigStrategy
    {
        public function render($template, array $context)
        {
            error_log("SEO Context: " . print_r($context, true));
            return parent::render($template, $context);
        }
    }
    

    Register it in services.yaml:

    services:
        Ayrel\SeoBundle\Twig\SeoTwigStrategy:
            alias: App\Twig\SeoDebugStrategy
    
  3. Fallback Values: Use {{ var|default('fallback') }} in Twig patterns to handle missing data:

    product:
        title: "{{product.title|default('No Title')}}"
    

Extension Points

  1. Custom Variables: Add global variables to SEO contexts via an event subscriber:

    // src/EventListener/SeoListener.php
    class SeoListener implements EventSubscriber
    {
        public static function getSubscribedEvents()
        {
            return [
                KernelEvents::CONTROLLER => 'onKernelController',
            ];
        }
    
        public function onKernelController(ControllerEvent $event)
        {
            $request = $event->getRequest();
            $request->attributes->set('_app_name', 'MyApp');
        }
    }
    

    Now use {{_app_name}} in SEO patterns.

  2. Dynamic Route Matching: Extend the route matcher to support regex or custom logic:

    // src/AyrelSeoBundle/DependencyInjection/Configuration.php
    // Override the route resolver logic
    
  3. Environment-Specific SEO: Use Symfony’s parameter system to switch SEO rules by environment:

    # config/packages/dev/ayrel_seo.yaml
    ayrel_seo:
        default:
            title: "Dev Mode: {_route}"
    

Performance

  • Avoid Heavy Twig Logic: Complex Twig patterns (e.g., loops, nested conditionals) in SEO tags can slow down rendering.
  • Pre-render Critical Tags: For high-traffic pages, pre-render SEO tags in a controller and pass them to Twig:
    public function indexAction()
    {
        $seo = [
            'title' => $this->renderSeoTitle(),
            'description' => $this->renderSeoDescription(),
        ];
        return $this->render('index.html.twig', ['seo' => $seo]);
    }
    
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