通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
[TOC] ## 静态方法 原始的方式,尽可能把方法转为静态,一般用于对类依赖不高的方法 ``` namespace App\Lib; class Add { public static function add(int $a,int $b){ return $a+$b; } } ``` //调用 ``` Add::add(1, 2);//3 ``` ## 依赖注入 缺陷是没有友好的代码提示 ``` namespace App\Lib; class Add { public function add(int $a,int $b){ return $a+$b; } } ``` ``` 注入容器 \EasySwoole\Component\Di::getInstance()->set("add",\App\Lib\Add::class); //调用容器中的方法 $add = \EasySwoole\Component\Di::getInstance()->get("add"); $add->add(1,2);//3 ``` ## 单例模式 可对无法做静态化的方法进行静态调用,用于复杂方法 ``` namespace App\lib; class Redis{ // 重点需要引入提供的单例 trait use \EasySwoole\Component\Singleton; public $redis; private function __construct(){ if(!extension_loaded("redis")){ throw new \Exception("redis.io 文件不存在"); } try{ $this->redis = new \Redis(); $result = $this->redis->connect("127.0.0.1", 6379, 3); } catch (\Exception $e){ throw new \Exception("redis 服务器异常"); } if ($result===false){ throw new \Exception("redis connect is failed"); } } public function get($key){ if (empty($key)) { return ''; } return $this->redis->get($key); } public function set($key, $value){ return $this->redis->set($key, $value); } } ``` 调用 ``` \App\Lib\Add::getInstance()->add(1, 2);//3 ```