symfony註入服務方式

2019-07-23 19:23:00
admin
來源:
https://www.it603.com/tw/js/96.html
轉自文章 1216

蔘考資料:

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


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


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