Search code examples
twigsymfony6

In Symfony 6 how to create a global variable which is coming from the database?


Currently i'm trying to create a variable which holdes a value that coming from the database which i need pretty much in all the views and controllers. Please help, I tried different solution like this one which seems a bit old symfony versions text.


Solution

  • You can create a Twig function to achieve this very easily. You will get the data at the exact place where you need them and you will not run it every time for all cost.

    Solution

    Create file `./src/Twig/{Something-like-Global}Extension.php

    <?php
    
    namespace My\Good\Namespace;
    
    use Doctrine\ORM\EntityManagerInterface;
    use Twig\Extension\AbstractExtension;
    use Twig\TwigFunction;
    
    class GlobalExtension extends AbstractExtension
    {
        public function __construct(
            protected readonly EntityManagerInterface $entityManager
        ) {}
    
        public function getFunctions(): array
        {
            return [
                new TwigFunction('myData', [$this, 'findMyData']),
            ];
        }
    
    
        public function findMyData(): string|null
        {
            return $this->entityManager->getRepository(...)->findBy([...]);
        }
    }
    

    For this to be registered as a Twig service, it must be a class extending Twig\Extension\AbstractExtension.

    Now you can call anywhere in file.ext.twig function like this

    Hello, my data are in a field
    
    {{ dump(myData()) }}
    
    and if I want to write them down, I can do
    
    {% for item in myData() %}
        {{ item.nameOfStringProperty }}
    {% else %}
        I was lying, I have no data
    {% endfor %}
    

    A note

    I am using PHP 8.2 here, so there might be some differences if you are using older version (namely the readonly keyword or how constructor works). If there will be only one repository, you can inject directly the repository. Entity Manager is good to inject if you'd be using many repositories and it would become chaotic to read.

    Why it is better than rewriting twig globally

    The benefit of this solution is that you will not get the database request all the time, but only if you need it. There might be one, two pages of your whole web that do not need it, therefore the data should not be retrieved at that stage.