前言:
门面模式是结构型设计模式的一种,亦称外观模式。它旨在为子系统的复杂操作提供一个统一的简化接口,从而降低客户端与子系统之间的耦合度,使客户端无需了解内部具体的调用细节。
举例:
可以将门面模式类比为电脑主机。用户启动应用仅需两步:按下开机键,待系统启动后打开应用。这里的“开机键”即为门面,背后隐藏了硬件自检、选择启动盘、加载引导程序、初始化内核及操作系统等一系列复杂模块。下文将通过邮件发送场景具体阐述该模式的应用。

涉及:
- call_user_func函数的使用
- 异常类的自定义处理
- 类的分层封装
- 发邮件功能的实现与配置
编码:
- 首先需通过Composer安装依赖库:composer require phpmailer/phpmailer。
- 建立扩展类目录,包含独立的配置文件、门面角色类、邮件核心功能类、参数校验类以及自定义异常类。

构建独立的配置类,用于存储SMTP服务地址、端口号、中转邮箱账号、授权码以及邮件发送者的昵称(作为唯一标识)。
<?php
/**
* @Notes: 邮箱SMTP服务配置
* @Interface getCondition
* @Return mixed
* @Author: bqs
* @Time: 2020/8/31 10:15
*/
return [
'smtp_server' => 'smtp.qq.com', // QQ邮箱开启的smtp
'smtp_port' => 465, // QQsmtp服务端口
'smtp_user' => '2652364582@qq.com', // 北桥苏邮箱
'smtp_pwd' => 'ynxdedefduuhecbj', // SMTP服务开启后授权码
'email_id' => '酷D' // 邮件发送者的唯一标识(自定义的昵称)
];
- 门面角色类是客户直接交互的入口,仅暴露一个发送方法。该方法内部协调调用校验逻辑与实际发送逻辑,对外屏蔽复杂性。
<?php
/**
* @Notes: 邮件门面
* @Interface getCondition
* @Return mixed
* @Author: bqs
* @Time: 2020/8/31 13:10
*/
namespace mail;
use think\Container;
use mail\facade\MailException;
use mail\facade\Mail;
use mail\facade\Validate;
class MailFacade
{
protected $error;
public static function __callStatic($method, $params)
{
//return (new static)->{$method}(...$params);
return call_user_func([new MailFacade(),$method],$params);
}
/**
* @Notes: 面向客户的邮件发送调用
* @Author: bqs
* @Time: 2026/8/31 13:33
* @Interface send
* @param $params
* @Return boolean 成功|失败
*/
private function send($params)
{
// 校验参数
$validate = Validate::make(__FUNCTION__);
$res = $validate->check($params);
if (!$res) {
// 抛出自定义异常
throw new MailException($validate->getError(),422);
return false;
}
// 发送邮件
$mail = new Mail();
$res = $mail->send($params);
return $res;
}
}
- 定义自定义异常类,以便在门面角色中抛出特定错误,并在客户端调用时进行捕获和错误消息输出处理。
<?php
/**
* @Notes: 邮件发送校验器
* @Interface getCondition
* @Return mixed
* @Author: bqs
* @Time: 2020/8/31 13:03
*/
namespace mail\facade;
class MailException extends \Exception
{
public function errorMessage()
{
return "mail error: ".$this->getMessage();
}
}
校验器负责验证客户传入参数的合法性,确保数据符合发送要求。
<?php
/**
* @Notes: 邮件发送校验器
* @Interface getCondition
* @Return mixed
* @Author: bqs
* @Time: 2020/8/31 13:03
*/
namespace mail\facade;
class Validate
{
protected $error;
protected $type; // 方法名
public function __construct($type)
{
$this->type = $type;
}
// 创建验证器对象
public static function make($type)
{
return new self($type);
}
// 与实际传入的参数做校验
public function check($params = [])
{
if (empty($params)) {
$this->error = "参数不足,非法请求";
}
$this->error = call_user_func([new self($this->type),$this->type],$params);
return $this->error ? false : true;
}
// 发送参数校验
public function send($params)
{
$res = "";
// 邮件
if (!isset($params[0]) || empty($params[0])) {
return "邮箱不能为空";
}
$email = [];
if (is_array($params[0])) {
$email = $params[0];
}else {
$email[0] = $params[0];
}
foreach ($email as $key => $val) {
if (!preg_match("/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$val)) {
return "邮箱格式不正确";
}
}
// 邮件标题
if (!isset($params[1]) || !$params[1]) {
return "邮件标题不能为空";
}
if (!isset($params[2]) || !$params[2]) {
return "邮件内容不能为空";
}
return $res;
}
// 获取错误信息
public function getError()
{
return $this->error;
}
}
- 实际的邮件发送逻辑依赖于PHPMailer库完成。
<?php
/**
* @Notes: 邮件实际发送
* @Interface getCondition
* @Return mixed
* @Author: bqs
* @Time: 2020/8/31 13:03
*/
namespace mail\facade;
use PHPMailer\PHPMailer\PHPMailer;
class Mail
{
protected $config = [];
public function __construct()
{
$this->config = include(dirname(__DIR__) . "../config/mail_config.php");
}
/**
* @Notes: 发邮件
* @Author: bqs
* @Time: 2026/8/31 13:07
* @Interface send
* @Return mixed
*/
public function send($params)
{
$to = $params[0]; // 接收者
$subject = $params[1]; // 邮件标题
$content = $params[2]; // 邮件内容
$emails = new PHPMailer();
$emails->CharSet = 'UTF-8'; //设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码
$emails->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$emails->SMTPDebug = 0;
//调试输出格式
//$emails->Debugoutput = 'html';
//smtp服务器
$emails->Host = $this->config['smtp_server'];
//端口 - likely to be 25, 465 or 587
$emails->Port = $this->config['smtp_port'];
if ($emails->Port === 465) $emails->SMTPSecure = 'ssl';// 使用安全协议
//Whether to use SMTP authentication
$emails->SMTPAuth = true;
//发送邮箱
$emails->Username = $this->config['smtp_user'];
//密码
$emails->Password = $this->config['smtp_pwd'];
//Set who the message is to be sent from
$emails->setFrom($this->config['smtp_user'], $this->config['email_id']);
//回复地址
//$emails->addReplyTo('replyto@example.com', 'First Last');
// 接收邮件方
if (is_array($to)) {
foreach ($to as $v) {
$emails->addAddress($v);
}
} else {
$emails->addAddress($to);
}
$emails->isHTML(true);// send as HTML
//标题
$emails->Subject = $subject;
//HTML内容转换
$emails->msgHTML($content);
//Replace the plain text body with one created manually
//$emails->AltBody = 'This is a plain-text message body';
//添加附件
//$emails->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
return $emails->send();
}
}
- 客户端调用部分的代码实现。
public function sendMail()
{
try {
$res = \mail\MailFacade::send(["1641181271@qq.com"], "测试标题", "测试内容");
var_dump($res);
die;
} catch (MailException $e) { // 捕捉自定义异常类抛出
var_dump($e->errorMessage());
die;
} catch (\Exception $e) {
var_dump($e->getMessage());
die;
}
}
- 当返回true表示发送成功,此时可检查收件箱以确认邮件是否接收。
环境要求:
邮件发送功能依赖于特定的运行环境和相关配置,以下补充实现成功发送所需的操作步骤。
第一步:访问官网下载PHPMailer。PHPMailer需要PHP的sockets扩展支持;若登录QQ邮箱SMTP服务器,必须通过SSL加密,因此PHP还需包含openssl扩展支持。

第二步:使用phpinfo()函数检查socket和openssl扩展信息(Wamp Server默认已启用)。若未开启openssl,需编辑php.ini文件:查找extension=php_openssl.dll,若存在则去除前面的分号注释符‘;’;若不存在,则手动添加该行。

PHPMailer 核心文件

第三步:**QQ 邮箱设置**。所有主流邮箱均支持SMTP协议,但并非默认开启,需在邮箱设置中手动激活。第三方服务提供账号和密码后即可登录SMTP服务器,控制邮件中转方式。
第四步:开启 SMTP 服务

选择 IMAP/SMTP 服务,点击开启服务。第五步:验证密保

发送短信“配置邮件客户端”至1069-0700-69。第六步:获取授权码

SMTP 服务器认证密码即授权码,使用时无空格,需妥善保管。
以上就是PHP门面模式实现简单的邮件发送示例的详细内容,更多关于PHP门面模式发送邮件的资料请关注本站其它相关文章!