参考资料:
https://symfony.com/doc/current/service_container/autowiring.html 注入方式
https://symfony.com/doc/current/service_container/injection_types.html 注入类型
1、Constructor injection 使用构造函数
通过构造方式传参的方式进行注入,推荐使用
public function __construct(MailerInterface $mailer) { $this->mailer = $mailer; }
2、Setter injection 使用setter方法
通过在service中定义方法调用的方式,主动调用传入依赖对象
public function setMailer(MailerInterface $mailer) { $this->mailer = $mailer; }
services: app.newsletter_manager: class: App\Mail\NewsletterManager calls: - [setMailer, ['@mailer']]
此方式还可以通过注解的方式对需要调用的方法进行定义(比在service中定义要方便)
private $kernel; /** * @Required * @param KernelInterface $kernel */ public function setKernel(KernelInterface $kernel) { $this->kernel = $kernel; }
3、Property Injection 直接设置属性
定义一个public属性并在service中定义该属性的值,此方式不推荐,但是可以有部分组件使用此方式,我们需要通过此方式对注入对象进行设置
class NewsletterManager{ public $mailer; }
services: app.newsletter_manager: class: App\Mail\NewsletterManager properties: mailer: '@mailer'
依赖注入的关键点在于依赖管理,通过将依赖处理交给统一机制的方式降低依赖。实现上则要依靠与(动态代理与动态字节码)(java)类似的技术。
推荐文章:https://www.cnblogs.com/huanxiyun/articles/5167430.html
技术
推荐
开发