symfony 4 使用服务设置全局设置以在 twig 中实现

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

我正在设置全局设置以在所有树枝模板中实现这一点。所以我也可以设置 error.html.twig 页。

我发现描述非常简短。 您在 twig.yaml 中实现全局变量,并为数据库中的变量编写服务。请看下面我的尝试 :) 但是它还没有用 :(

我认为我的服务写得不正确。请帮助:)

twig:

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

我的服务档案

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


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

        return $setting;
    }
}

随机 class 不能只在其方法中调用 $this->getDoctrine() 并期望得到一些对象。 PHP 现在如何从哪里得到它?代码检查/反射甚至会如何假设,getDoctrine 应该如何定义?

相反,您应该在构造函数中注入 EntityManagerInterface,因为这样,Symfony(框架)及其自动装配可以合理地识别您的服务的预期参数,并且类型提示会告诉它,注入什么:

<?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;
    }
}

希望对您有所帮助。

但是,潜在的问题是:您确定这是执行此操作的最佳方法吗?显然你有一整个 table 专用于你的网站设置,显然它只包含一行(这很可悲)。 Yaml 和 Symfony 有一些非常好的特性,你可以使用它们在配置本身或通过环境变量提供某些参数。但这超出了问题范围。