接口类,需要指定入参类型,出参类型
ThinkPHP6 短信发送工厂模式实现方案
根据你的需求,我设计了一套符合 接口规范 + 工厂模式 的短信发送方案,统一方法名和返回格式,支持动态切换腾讯云 / 阿里云接口,结构清晰且易于扩展。
一、目录结构(遵循 TP6 规范)
plaintext
app/
├── common/
│ └── lib/
│ ├── sms/
│ │ ├── contract/ # 接口契约
│ │ │ └── SmsInterface.php # 短信接口规范
│ │ ├── dto/ # 数据传输对象(统一返回格式)
│ │ │ └── SmsResult.php # 短信返回结构体
│ │ ├── impl/ # 第三方实现
│ │ │ ├── AliyunSms.php # 阿里云短信实现
│ │ │ └── TencentSms.php # 腾讯云短信实现
│ │ └── SmsFactory.php # 短信工厂类
├── config/
│ └── sms.php # 短信配置文件
└── controller/
└── TestController.php # 测试控制器

二、核心实现代码
1. 接口契约(统一方法规范)
app/common/lib/sms/contract/SmsInterface.phpphp
<?php
namespace app\common\lib\sms\contract;
use app\common\lib\sms\dto\SmsResult;
/**
* 短信发送接口规范
* 所有第三方短信实现必须遵循此接口
*/
interface SmsInterface
{
/**
* 发送短信
* @param string $phone 手机号(支持单个号码)
* @param string $templateId 模板ID
* @param array $templateParams 模板参数(键值对)
* @return SmsResult 统一返回结构体
*/
public function send(string $phone, string $templateId, array $templateParams): SmsResult;
}
2. 统一返回结构体(类似 Go 的 struct)
app/common/lib/sms/dto/SmsResult.phpphp
<?php
namespace app\common\lib\sms\dto;
/**
* 短信发送统一返回结构体
* 规范所有第三方返回格式,便于上层处理
*/
class SmsResult
{
// 状态码:200=成功,其他=失败
private int $code;
// 业务消息
private string $message;
// 第三方原始响应数据(便于调试)
private array $raw;
// 自定义扩展数据(如短信ID、回执ID等)
private array $extra = [];
public function __construct(int $code, string $message, array $raw = [], array $extra = [])
{
$this->code = $code;
$this->message = $message;
$this->raw = $raw;
$this->extra = $extra;
}
// 快捷创建成功结果
public static function success(string $message = '发送成功', array $raw = [], array $extra = []): self
{
return new self(200, $message, $raw, $extra);
}
// 快捷创建失败结果
public static function fail(string $message = '发送失败', array $raw = [], array $extra = []): self
{
return new self(500, $message, $raw, $extra);
}
// getter方法(只读,确保数据不可篡改)
public function getCode(): int
{
return $this->code;
}
public function getMessage(): string
{
return $this->message;
}
public function getRaw(): array
{
return $this->raw;
}
public function getExtra(): array
{
return $this->extra;
}
// 转为数组(便于接口返回)
public function toArray(): array
{
return [
'code' => $this->code,
'message' => $this->
