symfony注入服务方式

2019-07-21 17:17:00
CJL
原创
4956

参考资料:

https://symfony.com/doc/current/service_container/autowiring.html 注入方式

https://symfony.com/doc/current/service_container/injection_types.html 注入类型

https://stackoverflow.com/questions/46465820/symfony-autowire-required-method-with-event-dispatcher-never-called


依赖较多时建议通过第二种方式的注解进行注入


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;
}

注意:@required 注解必须严格匹配,r是小写 没有括号,且没有对应的注解类

具体解析代码见:vendor/symfony/dependency-injection/Compiler/AutowireRequiredMethodsPass.php


if (false !== stripos($doc, '@required') && preg_match('#(?:^/\*\*|\n\s*+\*)\s*+@required(?:\s|\*/$)#i', $doc)) {
    if (preg_match('#(?:^/\*\*|\n\s*+\*)\s*+@return\s++static[\s\*]#i', $doc)) {
        $withers[] = [$reflectionMethod->name, [], true];
    } else {
        $value->addMethodCall($reflectionMethod->name, []);
    }
    break;
}





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


发表评论
评论通过审核后显示。
流量统计