如何在自定义类中获取服务(依赖项) [英] How do I get services (dependencies) in a custom class

查看:22
本文介绍了如何在自定义类中获取服务(依赖项)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制器中,我可以做

$this->get('service.name')

但是在自定义类中,我该怎么做?

But in a custom class, how can I do that?

推荐答案

将自定义类定义为服务,然后向其中注入依赖项.

Define your custom class as a service, and then inject dependencies into it.

例如:

// services.yml
services:
   my.custom.service.id:
       class: My\Custom\Class
       arguments:
         - @service.name
         - @doctrine.orm.entity_manager

然后您的自定义类的构造函数将获取这些服务作为参数.

Your custom class' constructor would then get those services as arguments.

请务必阅读官方文档中的服务容器.它详细介绍了所有这些.

Be sure to read up on the Service Container in the official docs. It goes over all this in great detail.

这篇关于如何在自定义类中获取服务(依赖项)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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