🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 单例模式 可对无法做静态化的方法进行静态调用,用于复杂方法 ``` 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 ```