Skip to content

Instantly share code, notes, and snippets.

@hising
Last active February 5, 2020 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hising/ddece8c92bcd09df83fdcf9890fc0dd3 to your computer and use it in GitHub Desktop.
Save hising/ddece8c92bcd09df83fdcf9890fc0dd3 to your computer and use it in GitHub Desktop.
Slim 2 Memcached Cache Middleware
<?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();
}
}
@bitumin
Copy link

bitumin commented Feb 5, 2020

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;

@hising
Copy link
Author

hising commented Feb 5, 2020

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