Search code examples
symfonysettingssymfony4

symfony 4 setting up global settings with service to implement in twig


i am setting up global settings to reach for this in all twig templates. so i can also for example set the error.html.twig pages.

I found the description to do it very short. You implement the globals in twig.yaml and for variables from the db you write a service. see my attempt below :) however it's not working yet :(

i think my service isn;t written correclty. please help :)

twig:

  globals:
    setting: '@App\Service\Websitesettings'

my service file

<?php
namespace App\Service;
use App\Entity\Sitesetting;


class Websitesettings
{
    public function setting()
    {
        $setting = $this->getDoctrine()->getRepository(Sitesetting::class)
            ->findAll()[0];

        return $setting;
    }
}

Solution

  • a random class can't just call $this->getDoctrine() inside its methods and expect to get some object. How would PHP now where to get that from? How would a code inspection / reflection even assume, how getDoctrine is supposed to be defined?

    Instead, you should inject the EntityManagerInterface in the constructor, because this way, Symfony (the framework) and its autowiring can reasonable identify an expected parameter for your service, and the type hint will tell it, what to inject:

    <?php
    namespace App\Service;
    use Doctrine
    use Doctrine\ORM\EntityManagerInterface;
    
    
    class Websitesettings
    {
        /** @var EntityManagerInterface */
        public $em;
    
        public function __construct(EntityManagerInterface $em) {
            $this->em = $em;
        }
    
        public function setting()
        {
            $setting = $this->em->getRepository(Sitesetting::class)
                ->findAll()[0];
    
            return $setting;
        }
    }
    

    Hope that helps.

    However, the underlying question is: Are you sure this is the best way to do this? Apparently you have a whole table dedicated to your site settings, and apparently it only contains one row (which is quite sad). Yaml and Symfony have some very nice features, with which you could provide certain parameters in the config itself or via environment variables. But that goes beyond the question.