要求:
如果本次調用有緩存則返回緩存,沒有則從數據庫中查詢,寫入緩存
**傳統寫法**
~~~
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' => []
],
];
~~~