php - 接口依赖注入
问题描述
我正在考虑接口和依赖注入。到目前为止,我已经了解了接口的实现,但是在花了很多时间阅读和观看视频之后,我错过了一些东西并且无法超越它。我有一个很好的例子,它使用了不同的邮件服务,比如 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() 实现到第三方中,这感觉我的想法不对。我花了很多时间试图理解这个概念,但它从我的脑海中溜走。
我没有清楚地看到这一点,所以我的问题是如何设置我的第三方库以进行依赖注入?什么不见了?
解决方案
您无法获得 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);
推荐阅读
- python - 先执行测试用例
- ffmpeg - FFMPEG 在视频末尾添加图像
- java - 如何提高 jquery 数据表性能以高效加载 1,00,000 条记录的大数据
- python - 将不同类型的列表转换为 DataFrame
- django - Django 日期时间字段、时区字段和纪元
- arrays - 查找等于特定数字的所有数字组合
- javascript - 显示 Blob 图像 NodeJs React
- orientdb - 如何在 OrientDB 中找到连接最多的子节点
- php - 如何从 PHP 中的 JSON 服务器响应中获取数据
- java - Poi api XSSFWorkbook 表强制转换异常