Explorar o código

7-10短信验证码lib引入工厂模式

Home %!s(int64=5) %!d(string=hai) anos
pai
achega
f0c748e055

+ 1 - 1
app/api/controller/Sms.php

@@ -31,7 +31,7 @@ class Sms extends BaseController
         }
 
         // 调用business层
-        if (SmsBus::sendCode($phoneNumber, 6)) {
+        if (SmsBus::sendCode($phoneNumber, 6, 'jd')) {
             return show(config('status.success'), '发送验证码成功');
         }
         return show(config('status.success'), '发送验证码失败');

+ 9 - 3
app/common/business/Sms.php

@@ -9,18 +9,24 @@ declare(strict_types=1);
 
 namespace app\common\business;
 
-
 use AlibabaCloud\Client\Exception\ClientException;
 use app\common\lib\Num;
 use app\common\lib\sms\AliSms;
 
 class Sms
 {
-    public static function sendCode(string $phoneNumber, int $len): bool
+    public static function sendCode(string $phoneNumber, int $len, string $type = 'ali'): bool
     {
         // 生成短信验证码
         $code = Num::getCode($len);
-        $sms = AliSms::sendCode($phoneNumber, $code);
+        // 普通模式
+        // $sms = AliSms::sendCode($phoneNumber, $code);
+
+        // 工厂模式1
+        $type = ucfirst($type);
+        $class = "app\common\lib\sms\{$type}Sms";
+        $sms = $class::sendCode($phoneNumber, $code);
+
         if ($sms) {
             // 将验证码记录到redis,并设置失效时间
             // 检查php环境是否有redis拓展

+ 1 - 1
app/common/lib/sms/AliSms.php

@@ -15,7 +15,7 @@ use AlibabaCloud\Client\Exception\ClientException;
 use AlibabaCloud\Client\Exception\ServerException;
 use think\facade\Log;
 
-class AliSms
+class AliSms implements SmsBase
 {
     /**
      * 阿里云发送验证码的场景

+ 21 - 0
app/common/lib/sms/BaiduSms.php

@@ -0,0 +1,21 @@
+<?php
+/**
+ * Created by PhpStorm
+ * User:林志杰
+ * Email:[email protected]
+ * Motto:纵有疾风起,人生不言弃!
+ * Time:2020/2/8 0:23
+ */
+
+declare(strict_types=1);
+
+namespace app\common\lib\sms;
+
+
+class BaiduSms implements SmsBase
+{
+    public static function sendCode(string $phone, int $code): bool
+    {
+        return true;
+    }
+}

+ 21 - 0
app/common/lib/sms/JdSms.php

@@ -0,0 +1,21 @@
+<?php
+/**
+ * Created by PhpStorm
+ * User:林志杰
+ * Email:[email protected]
+ * Motto:纵有疾风起,人生不言弃!
+ * Time:2020/2/8 0:23
+ */
+
+declare(strict_types=1);
+
+namespace app\common\lib\sms;
+
+
+class JdSms implements SmsBase
+{
+    public static function sendCode(string $phone, int $code): bool
+    {
+        return true;
+    }
+}

+ 18 - 0
app/common/lib/sms/SmsBase.php

@@ -0,0 +1,18 @@
+<?php
+/**
+ * Created by PhpStorm
+ * User:林志杰
+ * Email:[email protected]
+ * Motto:纵有疾风起,人生不言弃!
+ * Time:2020/2/8 0:23
+ */
+
+declare(strict_types=1);
+
+namespace app\common\lib\sms;
+
+
+interface SmsBase
+{
+    public static function sendCode(string $phone, int $code): bool;
+}