Access services inside a regular class(在普通班级内访问服务)
问题描述
我的 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.
这篇关于在普通班级内访问服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在普通班级内访问服务
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
- PHP Count 布尔数组中真值的数量 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Laravel 仓库 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01