Last active
February 5, 2020 14:36
-
-
Save hising/ddece8c92bcd09df83fdcf9890fc0dd3 to your computer and use it in GitHub Desktop.
Slim 2 Memcached Cache Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Doon\Middleware; | |
use Memcached; | |
class Cache extends \Slim\Middleware { | |
protected $memcached, $settings, $ttl; | |
public function __construct($settings) | |
{ | |
$host = isset($settings['host']) ? $settings['host'] : '127.0.0.1'; | |
$port = isset($settings['port']) ? $settings['port'] : 11211; | |
$this->ttl = isset($settings['ttl']) ? $settings['ttl'] : 3600; | |
$this->settings = $settings; | |
$this->memcached = new Memcached(); | |
$this->memcached->addServer($host, $port); | |
} | |
public function call() { | |
$app = $this->app; | |
$request = $app->request; | |
if (!$request->isGet()) { | |
$this->next->call(); | |
return; | |
} | |
$rootUri = $request->getRootUri(); | |
$host = $request->getHostWithPort(); | |
$scheme = $request->getScheme(); | |
$resourceUri = $request->getResourceUri(); | |
$queryString = isset($_SERVER['QUERY_STRING']) ? "?" . $_SERVER['QUERY_STRING'] : ""; | |
$cacheKey = hash('md5', $scheme."://".$host.$rootUri.$resourceUri.$queryString); | |
$response = $app->response(); | |
if($data = $this->memcached->get($cacheKey)) { | |
foreach ($data['header'] as $key => $value) { | |
$response->headers->set($key, $value); | |
} | |
$response->body($data["body"]); | |
} else if ($response->status() == 200) { | |
$header = $response->headers->all(); | |
$data = array( | |
'header' => $header, | |
'body' => $response->body() | |
); | |
$this->memcached->set($cacheKey, $data, $this->ttl); | |
} | |
$this->next->call(); | |
} | |
} |
Hi, I believe there is an errata with the name of the key to retrieve the expiration time setting from the settings array ('port' is a bit misleading)
$this->ttl = isset($settings['port']) ? $settings['port'] : 3600;
Nice catch! I changed it. Thx
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I believe there is an errata with the name of the key to retrieve the expiration time setting from the settings array ('port' is a bit misleading)
$this->ttl = isset($settings['port']) ? $settings['port'] : 3600;