在控制器中,我能做到
$this->get('service.name')
Run Code Online (Sandbox Code Playgroud)
但在自定义课程中,我该怎么做?
Ste*_*nte 26
将自定义类定义为服务,然后将依赖项注入其中.
例如:
// services.yml
services:
my.custom.service.id:
class: My\Custom\Class
arguments:
- @service.name
- @doctrine.orm.entity_manager
Run Code Online (Sandbox Code Playgroud)
然后,您的自定义类的构造函数将获取这些服务作为参数.
请务必阅读官方文档中的服务容器.它非常详细地讨论了这一切.
您使用ContainerAware进入了正确的轨道.
$this->get('id')实际上是一个快捷方式$this->container->get('id').将容器放入您的课程就像实施一样简单ContainerAwareInterface- 将此片段放入您的班级:
public function setContainer(\Symfony\Component\DependencyInjection\ContainerInterface $container = null)
{
$this->container = $container;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20786 次 |
| 最近记录: |