在普通班级内访问服务班级、普通

2023-09-08 08:43:15 作者:深知你是梦

我的 Symfony2 项目中有一个常规课程:

I have a regular class in my Symfony2 project:

    class RangeColumn extends Column{
        //...
    }

现在这个类里面有一个渲染函数,我想在其中使用 Twig 或 Symfony2 的翻译服务来渲染一个特定的模板.如何以正确的方式访问这些服务?

Now inside this class is a render function, in which I'd like to use Twig or the Translation Service of Symfony2 to render a specific template. How do I access this services in a proper way?

推荐答案

使用 依赖注入.这是一个非常简单的概念.

Use dependency injection. It's a really simple concept.

您应该简单地将所需的服务传递(注入)给您的班级.

You should simply pass (inject) needed services to your class.

如果依赖项是强制,则将它们传递给构造函数.如果它们是可选,请使用setter.

If dependencies are obligatory pass them in a constructor. If they're optional use setters.

您可能会更进一步,将您的类的构造委托给依赖注入容器(从中创建一个服务).

You might go further and delegate construction of your class to the dependency injection container (make a service out of it).

服务与您的常规"课程没有什么不同.只是他们的构造委托给了容器.

Services are no different from your "regular" class. It's just that their construction is delegated to the container.

 
精彩推荐
图片推荐