如何将“模板”组件作为参数传递给服务?

时间:2014-08-19 18:49:13

标签: symfony

我在'DynamicList'服务中有一个方法,它应该返回一个填充了动态数据的选择,但是我得到了“循环引用”:

YML:

parameters:
    my.dynamic_list.class: My\DynamicListBundle\Service\DynamicList

services:
    my.dynamic_list:
        class: %my.dynamic_list.class%
        arguments: ['@doctrine.orm.default_entity_manager','@templating']

类别:

<?php

namespace My\DynamicListBundle\Service;

use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

class DynamicList
{
    private $em;
    private $templating;

    public function __construct(
        EntityManager $em,
        EngineInterface $templating
    ) {
        $this->em = $em;
        $this->templating = $templating;
    }

    public function getSelect($slug)
    {
        $dynamic_list = $this->em
            ->getRepository('MyDynamicListBundle:DynamicList')
            ->findOneBy(array(
                "slug" => $slug
            ));

        return $this->templating->render('MyComponentsCoreBundle::Templates/DynamicList/combo.html.twig', array(
            'dl' => $dynamic_list
        ));
    }
}

我想我不需要把枝条内容放在这里:问题出现在之前。

最后,我得到的错误:

Circular reference detected for service "my.dynamic_list", path: "my.dynamic_list -> templating -> twig". (500 Internal Server Error - ServiceCircularReferenceException)

在我的服务中使用模板组件的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

好吧,我发现了一种解决方法,但如果是最好的方式,我不会这样做:

<?php

namespace My\DynamicListBundle\Service;

use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

class DynamicList
{
    private $em;
    private $templating;

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

    public function init(
        EngineInterface $templating
    ) {
        $this->templating = $templating;
    }

    public function getSelect($slug)
    {
        $dynamic_list = $this->em
            ->getRepository('MyDynamicListBundle:DynamicList')
            ->findOneBy(array(
                "slug" => $slug
            ));

        return $this->templating->render('MyComponentsCoreBundle::Templates/DynamicList/combo.html.twig', array(
            'dl' => $dynamic_list
        ));
    }
}

所以,在控制器中,我调用'init()'来传递'模板':

$dl_service = $this->get('my.dynamic_list');
$dl_service->init($this->container->get('templating'));