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

Page Metadata Bundle Laravel Package

druidvav/page-metadata-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the bundle via Composer:

    composer require druidvav/page-metadata-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Druidvav\PageMetadataBundle\DruidvavPageMetadataBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Publish the default config (if needed) and adjust in config/page_metadata.php:

    php bin/console druidvav:page-metadata:install
    

    Key settings:

    # config/page_metadata.yaml
    default_metadata:
        title: "Default Title"
        description: "Default Description"
        keywords: "default,keywords"
        robots: "index,follow"
    
  3. First Use Case: Adding Metadata to a Controller Use the Metadata trait in a controller to inject metadata:

    use Druidvav\PageMetadataBundle\Metadata\Metadata;
    
    class HomeController extends AbstractController
    {
        use Metadata;
    
        public function index(): Response
        {
            $this->setMetadata([
                'title' => 'Home Page',
                'description' => 'Welcome to our site!',
            ]);
            return $this->render('home/index.html.twig');
        }
    }
    
  4. Twig Integration Verify metadata is rendered in your base template (e.g., base.html.twig):

    <title>{{ page_metadata.title }}</title>
    <meta name="description" content="{{ page_metadata.description }}">
    

Implementation Patterns

1. Dynamic Metadata by Route/Controller

  • Route-Based Metadata: Use the Metadata trait to set metadata per action:

    public function about(): Response
    {
        $this->setMetadata([
            'title' => 'About Us',
            'description' => 'Learn about our company.',
            'keywords' => 'about,team,history',
        ]);
        return $this->render('about/index.html.twig');
    }
    
  • Global Overrides: Extend the Metadata trait to modify behavior:

    trait CustomMetadata
    {
        use Metadata;
    
        protected function getDefaultMetadata(): array
        {
            return array_merge(parent::getDefaultMetadata(), [
                'author' => 'Your Company',
            ]);
        }
    }
    

2. Integration with Symfony Events

  • Pre-Render Hooks: Attach metadata dynamically via kernel events:
    // src/EventListener/MetadataListener.php
    public function onKernelController(ControllerEvent $event)
    {
        $controller = $event->getController();
        if (is_array($controller)) {
            $this->setMetadataForController($controller[0]);
        }
    }
    

3. Reusing Metadata Across Templates

  • Template Inheritance: Define metadata in parent templates and override in children:
    {# base.html.twig #}
    <title>{{ page_metadata.title | default('Default Title') }}</title>
    
    {# child.html.twig #}
    {% set page_metadata.title = 'Custom Title' %}
    

4. API/JSON Responses

  • Exclude Metadata for APIs: Filter metadata based on request type:
    if ($this->isJsonRequest()) {
        $this->setMetadata(['robots' => 'noindex']);
    }
    

5. Localization Support

  • Translatable Metadata: Use Symfony’s translation system:
    $this->setMetadata([
        'title' => $this->translator->trans('page.title'),
    ]);
    

Gotchas and Tips

1. Configuration Quirks

  • Default Values: Ensure default_metadata is set in config/page_metadata.yaml to avoid runtime errors.
  • Override Priority: Controller-level metadata overrides global defaults, but Twig {% set %} takes precedence over both.

2. Debugging

  • Missing Metadata: Check if the Metadata trait is properly used in controllers. Verify the bundle is enabled in bundles.php.
  • Twig Variables: Ensure page_metadata is passed to Twig templates. Debug with:
    {{ dump(page_metadata) }}
    

3. Performance

  • Avoid Overhead: Cache metadata for static pages or use Symfony’s cache system to store frequently used metadata.

4. Extension Points

  • Custom Metadata Fields: Extend the Metadata class to support additional fields (e.g., OpenGraph tags):
    // src/Metadata/CustomMetadata.php
    class CustomMetadata extends Metadata
    {
        protected $customFields = ['og:image', 'twitter:card'];
    
        public function setOgImage(string $url): self
        {
            $this->metadata['og:image'] = $url;
            return $this;
        }
    }
    

5. Common Pitfalls

  • Case Sensitivity: Metadata keys (e.g., title, description) are case-sensitive in Twig.
  • Double Rendering: Avoid calling setMetadata() multiple times in the same action unless merging data:
    $this->setMetadata($this->getDefaultMetadata());
    $this->setMetadata(array_merge($this->getMetadata(), ['title' => 'New Title']));
    

6. Testing

  • Unit Tests: Mock the Metadata trait to test metadata logic:
    $controller = $this->getMockBuilder(HomeController::class)
        ->onlyMethods(['setMetadata'])
        ->getMock();
    $controller->setMetadata(['title' => 'Test']);
    $this->assertEquals('Test', $controller->getMetadata()['title']);
    

7. Bundle Limitations

  • No Built-in Cache: Manually cache metadata if performance is critical.
  • Limited Documentation: Refer to the source code for undocumented features (e.g., event listeners).
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