接口依赖注入

时间:2019-09-03 04:44:17

标签: php dependency-injection

我全神贯注于接口和依赖注入。到目前为止,我已经了解了接口实现的功能,但是在花费大量时间阅读和观看视频之后,我还是错过了一些东西并且无法超越它。 我有一个很好的示例,该示例使用了第三方库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);
    }
}

现在需要在Mailer服务中实现此MailerInterface,但这是第三方。而且我还需要将该函数send()实施到第三方中,这感觉好像我在想的不对。我花了很多时间来尝试理解这个概念,但是它却从我的头上溜了下来。

我没有清楚地看到这一点,所以我的问题是如何为依赖项注入设置第三方库?缺少什么?

1 个答案:

答案 0 :(得分:2)

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

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