简体   繁体   English

Symfony Twig全局变量

[英]Symfony Twig global variables

I'm trying to call some data in my root twig template and used Twig global variables to achieve that. 我试图在根Twig模板中调用一些数据,并使用Twig全局变量来实现这一点。

When I call the service i get this error: 当我致电服务时,出现此错误:

Type error: Argument 1 passed to AwarenessBundle\\Service\\AwarenessService::getLatestNews() must implement interface Doctrine\\ORM\\EntityManagerInterface, none given, called in /var/www/html/myisms/vendor/twig/twig/lib/Twig/Template.php on line 675 类型错误:传递给AwarenessBundle \\ Service \\ AwarenessService :: getLatestNews()的参数1必须实现接口Doctrine \\ ORM \\ EntityManagerInterface,未给出接口,在/ var / www / html / myisms / vendor / twig / twig / lib / Twig /中调用675行上的Template.php

Twig code: 树枝代码:

{{ news_service.getlatestNews() }}

services.yml: 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));
    }
}

I'm not sure where my problem is but I have to make my service global and I don't know how to do that. 我不确定我的问题在哪里,但是我必须使服务全球化,而且我不知道该怎么做。 Any help would be appreciated. 任何帮助,将不胜感激。

Pass EntityManagerInterface to your service constructor(instead of getLatestNews method), like this: 将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: Service.yml:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM