在普通班级内访问服务 [英] Access services inside a regular class

查看:24
本文介绍了在普通班级内访问服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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.

这篇关于在普通班级内访问服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆