首页 > 解决方案 > 接口依赖注入

问题描述

我正在考虑接口和依赖注入。到目前为止,我已经了解了接口的实现,但是在花了很多时间阅读和观看视频之后,我错过了一些东西并且无法超越它。我有一个很好的例子,它使用了不同的邮件服务,比如 PHPMailer 或 OtherMailerService,它们是第三方库。我不会从我的类(SomeClass)中实例化邮件服务,而是将一个实例注入到构造函数中,为了使其灵活,我将使用一个接口。

<?php
interface MailerInterface {
    public function send($message);
}

我现在可以对类的构造函数参数进行类型提示以保护我的类。

<?php
class SomeClass{
    public $mailer;
    public function __construct(MailerInterface $mailer) { 
        $this->mailer = $mailer;
    }
    public function sendMailMessage() 
    {
        $mailer->send($message);
    }
}

现在这个 MailerInterface 需要在 Mailer 服务中实现,但这是第三方。而且我还需要将该函数 send() 实现到第三方中,这感觉我的想法不对。我花了很多时间试图理解这个概念,但它从我的脑海中溜走。

我没有清楚地看到这一点,所以我的问题是如何设置我的第三方库以进行依赖注入?什么不见​​了?

标签: phpdependency-injection

解决方案


您无法获得 3rd 方库来实现您的接口,因此您需要编写一些包装类,例如

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

对于您希望支持的任何其他实现,您需要做类似的事情。

然后,您将创建这些实现之一的实例并将其传递给您的SomeClass构造函数,例如

$mailer = new PHPMailerWrapper($phpMailerInstance);
$someObj = new SomeClass($mailer);

推荐阅读