<?php
namespace Core\Middleware;
class Cache
{
protected $db;
public function __construct($db) {
$this->db = $db;
}
* Example middleware invokable class
*
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response
* @param callable $next Next middleware
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke($request, $response, $next)
{
$path = $request->getUri()->getPath();
$query= $request->getUri()->getQuery();
if(!empty($query)){
$path.='?'.$query;
}
$cachetime=time()-60;
$cache=$this->db->get('cache','*',['AND'=>['path'=>$path,'created_at[>]'=>$cachetime]]);
if($cache){
$t2=microtime(true);
$response->getBody()->write(htmlspecialchars_decode($cache['body']).
'<!--cached at'.date("Y/m/d H:i:s",$cache['created_at']).'-->
<!--app cost time '.(round(($t2-APP_START),5)*1000).'ms-->');
return $response;
}
$response = $next($request, $response);
if ($response->getStatusCode() == 200) {
$id=$this->db->get('cache','id',['path'=>$path]);
$cachebody=htmlspecialchars($response->getBody());
$data=['path'=>$path,'body'=>$cachebody,'created_at'=>time()];
if($id){
$this->db->update('cache',$data,['id'=>$id]);
}else{
$this->db->insert('cache',$data);
}
}
$t2=microtime(true);
$response->getBody()->write('<!--no cache app cost time '
.(round(($t2-APP_START),5)*1000).'ms-->');
return $response;
}
}