Symfony Twig全局变量

时间:2017-08-14 11:20:01

标签: symfony service doctrine twig global-variables

我试图在我的根树枝模板中调用一些数据并使用Twig全局变量来实现这一点。

当我调用该服务时,我收到此错误:

  

类型错误:传递给AwarenessBundle \ Service \ AwarenessService :: getLatestNews()的参数1必须实现接口Doctrine \ ORM \ EntityManagerInterface,没有给出,在/ var / www / html / myisms / vendor / twig / twig / lib中调用第675行/Twig/Template.php

Twig代码:

{{ news_service.getlatestNews() }}

services.yml:

news.latest:
    class: AwarenessBundle\Service\AwarenessService
    arguments: [ '@doctrine.orm.entity_manager' ]

AwarenessService

class AwarenessService 
{
    public function getLatestNews(EntityManagerInterface $em)
    {
        return $em->getRepository("AwarenessBundle:Feed")
            ->findBy(array(), array('id' => 'DESC', 10));
    }
}

我不确定我的问题在哪里,但我必须让我的服务全球化,而且我不知道该怎么做。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

将EntityManagerInterface传递给服务构造函数(而不是getLatestNews方法),如下所示:

   class AwarenessService 
    {
        /**
         * @var EntityManagerInterface
         */
        protected $em;

        public function __construct(EntityManagerInterface $em){
             $this->em = $em;
        }

        public function getLatestNews() {

            return $this->em->getRepository("AwarenessBundle:Feed")
                ->findBy(array(), array('id' => 'DESC', 10));

        }

}

Service.yml:

news.latest:
    class: AwarenessBundle\Service\AwarenessService
    //arguments for constructor!
    arguments: [ '@doctrine.orm.entity_manager' ]