第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

接口依賴注入

接口依賴注入

PHP
Helenr 2021-12-24 09:52:10
我正在研究接口和依賴注入。到目前為止,我知道接口的實現(xiàn)做了什么,但是我錯過了一些東西并且在花了很多時間閱讀和觀看視頻之后無法通過它。我有一個很好的例子,它使用不同的郵件服務(wù),比如 PHPMailer 或 OtherMailerService,它們是第三方庫。我不會在我的類(SomeClass)中實例化郵件服務(wù),而是將一個實例注入到構(gòu)造函數(shù)中,為了使其靈活,我將使用一個接口。<?phpinterface MailerInterface {    public function send($message);}我現(xiàn)在可以鍵入提示我的類的構(gòu)造函數(shù)參數(shù)來保護我的類。<?phpclass SomeClass{    public $mailer;    public function __construct(MailerInterface $mailer) {         $this->mailer = $mailer;    }    public function sendMailMessage()     {        $mailer->send($message);    }}現(xiàn)在這個 MailerInterface 需要在 Mailer 服務(wù)中實現(xiàn),但這是第三方。而且我還需要將該函數(shù) send() 實現(xiàn)到第三方中,這感覺就像我認(rèn)為的不對。我花了很多時間試圖獲得這個概念,但它從我的腦海中溜走。我沒有清楚地看到這一點,所以我的問題是如何為依賴注入設(shè)置第三方庫?缺什么?
查看完整描述

1 回答

?
人到中年有點甜

TA貢獻1895條經(jīng)驗 獲得超7個贊

您無法獲得第 3 方庫來實現(xiàn)您的接口,因此您需要編寫一些包裝類,例如


use PHPMailer\PHPMailer\PHPMailer;


class PHPMailerWrapper implements MailerInterface {

    private $mail;


    public function __construct(PHPMailer $mail) {

        $this->mail = $mail;

        // mailer could be configured here or prior to being passed in here

    }


    public function send($message) {

        // super simple example, I don't know PHPMailer very well

        $this->mail->body = $message;

        return $this->mail->send();

    }

}

您需要為您希望支持的任何其他實現(xiàn)做類似的事情。


然后,您將創(chuàng)建這些實現(xiàn)之一的實例并將其傳遞給您的SomeClass構(gòu)造函數(shù),例如


$mailer = new PHPMailerWrapper($phpMailerInstance);

$someObj = new SomeClass($mailer);


查看完整回答
反對 回復(fù) 2021-12-24
  • 1 回答
  • 0 關(guān)注
  • 153 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號