简体   繁体   English

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

[英]Cannot redeclare class in Symfony2 Twig extension

I'm creating a Twig extension and activating it with a service. 我正在创建一个Twig扩展并使用服务激活它。 Everything works great except I'm trying to simply use another class from my Twig extension. 一切都很好,除了我试图简单地使用我的Twig扩展中的另一个类。

The idea is to instantiate the new class then use it as needed. 我们的想法是实例化新类,然后根据需要使用它。 Instantiating is a problem as it errors with: 实例化是一个问题,因为它错误:

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

Surely it instantiates it once. 当然它会实例化一次。 Why is this happening? 为什么会这样?

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.

You should make your NewClass into a service and then inject that and the @request service into your twig extension rather than the container. 您应该将NewClass转换为服务,然后将该@request@request服务注入您的@request扩展而不是容器中。 Injecting the container directly is a bad idea apparently. 直接注入容器显然是一个坏主意。

For example in your services.. 例如在您的服务中..

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 }

And then in your 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.

In your NewClass: 在你的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.
    }

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

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