symfony註入服務方式

2019-07-21 17:17:00
CJL
原創
4962

蔘考資料:

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


發錶評論
評論通過審核後顯示。
流量統計