Browse Source

7-11利用反射机制处理工厂模式

Home 5 years ago
parent
commit
d7df3f4491
2 changed files with 63 additions and 2 deletions
  1. 9 2
      app/common/business/Sms.php
  2. 54 0
      app/common/lib/ClassArr.php

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

@@ -5,11 +5,13 @@
  * Email: [email protected]
  * Time: 2020/1/11 17:56
  */
+
 declare(strict_types=1);
 
 namespace app\common\business;
 
 use AlibabaCloud\Client\Exception\ClientException;
+use app\common\lib\ClassArr;
 use app\common\lib\Num;
 use app\common\lib\sms\AliSms;
 
@@ -23,8 +25,13 @@ class Sms
         // $sms = AliSms::sendCode($phoneNumber, $code);
 
         // 工厂模式1
-        $type = ucfirst($type);
-        $class = "app\common\lib\sms\{$type}Sms";
+        // $type = ucfirst($type);
+        // $class = "app\common\lib\sms\{$type}Sms";
+        // $sms = $class::sendCode($phoneNumber, $code);
+
+        // 工厂模式2
+        $classStats = ClassArr::smsClassStat();
+        $class = ClassArr::initClass($type, $classStats);
         $sms = $class::sendCode($phoneNumber, $code);
 
         if ($sms) {

+ 54 - 0
app/common/lib/ClassArr.php

@@ -0,0 +1,54 @@
+<?php
+/**
+ * Created by PhpStorm
+ * User:林志杰
+ * Email:[email protected]
+ * Motto:纵有疾风起,人生不言弃!
+ * Time:2020/2/8 0:44
+ */
+
+declare(strict_types=1);
+
+namespace app\common\lib;
+
+
+class ClassArr
+{
+    public static function smsClassStat(): array
+    {
+        return [
+            "ali" => "app\common\lib\sms\AliSms",
+            "baidu" => "app\common\lib\sms\BaiduSms",
+            "jd" => "app\common\lib\sms\JdSms",
+        ];
+    }
+
+    public static function uploadClassStat(): array
+    {
+        return [
+            'text' => 'xxx',
+            'image' => 'xxx',
+        ];
+    }
+
+    /**
+     * @param string $type
+     * @param array $class
+     * @param array $params 实例化的参数
+     * @param bool $needInstance 是否需要实例化
+     * @return bool|mixed|object
+     * @throws \ReflectionException
+     */
+    public static function initClass(string $type, array $class, array $params = [], bool $needInstance = false)
+    {
+        // 如果工厂模式调用的方法是静态的,那么我们这个地方返回类库AliSms
+        // 如果不是静态的呢,我们就需要返回 对象
+        if (!array_key_exists($type, $class)) {
+            return false;
+        }
+        $className = $class[$type];
+        // new \ReflectionClass('A') => 简历A的反射类
+        // ->newInstanceArgs($args) => 返回A的实例化对象,$args是实例化时传入的参数
+        return $needInstance === true ? (new \ReflectionClass('AliSms'))->newInstanceArgs($params) : $className;
+    }
+}