无法在Symfony2 Twig扩展中重新声明类

时间:2013-03-30 10:25:56

标签: symfony twig

我正在创建一个Twig扩展并使用服务激活它。一切都很好,除了我试图简单地使用我的Twig扩展中的另一个类。

想法是实例化新类,然后根据需要使用它。实例化是一个问题,因为它出错:

Error: Cannot redeclare class NewClass in .../Bundle/NewClass.php line 13

肯定会实例化一次。为什么会这样?

namespace Bundle\Twig;

use Bundle\NewClass;

class NewExtension extends \Twig_Extension
{

    private $request;
    private $new_class;

    public function __construct($container) {

        //get the Request object   
        $this->request = $container->get('request');

        //instantiate new class
        $this->new_class = new NewClass();  // this part triggers the error

    }

    ///etc.

1 个答案:

答案 0 :(得分:2)

您应该将NewClass放入服务中,然后将该@request服务注入您的树枝扩展名而不是容器中。直接注入容器显然是一个坏主意。

例如在您的服务中..

services:
    # create new class as a instantiated service
    acme_demo.new_class:
        class: Acme\DemoBundle\NewClass
        arguments: [ '@request' ]

    acme_demo.twig.acme_extension:
        class: Acme\DemoBundle\Twig\AcmeExtension
        arguments: [ '@request', '@acme_demo.new_class' ]
            # inject the Request service and your class from above
        tags:
            - { name: twig.extension }

然后在你的Twig扩展中

namespace Bundle\Twig;

use Bundle\NewClass;

class NewExtension extends \Twig_Extension
{
    private $new_class;

    public function __construct(NewClass $newClass) {
        $this->new_class = $newClass;
    }

    ///etc.

在你的NewClass中:

namespace Bundle;

class NewClass
{
    private $param1;
    private $param2;

    public function __construct(Request $request)
    {
        $this->param1 = $request->get('param1');
        $this->param2 = $request->get('param2');

        // You could also add some check in here to make sure they are valid.
    }