发布时间:2025-12-09 14:08:33 浏览次数:6
场景:使用工厂模式接入:阿里短信验证、腾讯短信验证、百度短信验证
BaseSMS.php – 基础短信服务接口类AliSMS.php – 阿里短信服务类BaiduSMS.php – 百度短信服务类TencentSMS.php – 腾讯短信服务类SmsBusiness.php – 短信业务逻辑类BaseSMS.php – 基础短信服务接口类
interface BaseSMS{ public static function sendCode($phone, $code);}AliSMS.php – 阿里短信服务类
class AliSMS implements BaseSMS{ public static function sendCode($phone, $code){ // 这里是阿里云短信服务代码// XXXXXXXXXXXXXXXXXXXXXreturn '阿里云短信验证码发送成功';}}BaiduSMS.php – 百度短信服务类
class BaiduSMS implements BaseSMS{ public static function sendCode($phone, $code){ // 这里是百度云短信服务代码// XXXXXXXXXXXXXXXXXXXXXreturn '百度云短信验证码发送成功';}}TencentSMS.php – 腾讯短信服务类
class TencentSMS implements BaseSMS{ public static function sendCode($phone, $code){ // 这里是腾讯云短信服务代码// XXXXXXXXXXXXXXXXXXXXXreturn '腾讯云短信验证码发送成功';}}SmsBusiness.php – 短信业务逻辑类
class SmsBusiness{ public static function sendCode($phone, $len = 4, $type){ // 生成短信验证码$code = mt_rand(1000,9999); // 默认为4位数验证码if ($len == 6){ // 长度为6,则生成6位数验证码$code = mt_rand(100000,999999);}// 工厂模式创建不同的短信服务商$smsObj = null;switch($type){ case 'ali':$smsObj = new AliSMS();break;case 'baidu':$smsObj = new BaiduSMS();break;case 'tencent':$smsObj = new TencentSMS();break;}$sms = $smsObj::sendCode($phone, $code);if ($sms) { // 成功:把短信验证码记录到 redis, 并且设置失效时间 cache(config('stores.redis.prefix') . $phone, $code, config('stores.redis.expire')); }return true;}}最后,控制器调用 业务逻辑层短信发送验证码服务
class SMSController { public function code (){ $phone = request()->param('phone_number', '', 'trim');/* * 这里是参数验证,略 */// 调用业务逻辑层的sendCode if (SmsBusiness::sendCode($phoneNumber, config('code.code.length'), 'ali')){ return show(config('status.success'), '验证码发送成功'); } return show(config('status.error'), '验证码发送失败');}}——- THE END ——-