💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
要求: 如果本次调用有缓存则返回缓存,没有则从数据库中查询,写入缓存 **传统写法** ~~~ class Demo{ public function news() { $data = Cache('xxx'); if ( ! $data) { // 查询数据库并写入缓存中 $data = '此处省略查询数据库过程'; Cache('xxx', $data); } json($data); } } ~~~ **中间件写法** ~~~ namespace middleware; class Middleware{ // 创建中间件 public function cache($hash = '') { $data = Cache($hash); if ($data !== FALSE) { json($data); return TRUE; } } } // 控制器 class Demo{ public function news() { $data = '此处省略查询数据库过程'; Cache('xxx', $data); json($data); } } // 配置文件中注册前置中间件 return [ ... // 默认中间件 'MIDDLEWARE' => [ // 注册前置缓存中间件 'BEFORE' => [ 'cache' ], 'AFTER' => [] ], ]; ~~~