如何在Fat-free Framework中强制清除动态URL的缓存?
How do i clear the cache of my patterned url (dynamic url)?
Like, /assets/js/@jsname.js
...
I don't want to wait until the cache expired, i want to it, immediately after i updated things on my database.
They said that to clear the database, you need to specify the key for it. And i don't know what should i enter for the key :(
Here's my code:
\F3::route("GET @virtualasset: /assets/img/@link/@size.@id.@type", "Control\\Imager->akses", 3600 * 24 * 7); // cache seminggu :3
HTTP responses are cached using the following key: hash(VERB URI).url
.
So if you want to refresh assets/js/foo.js
, you'll have to do:
$hash=$f3->hash('GET /assets/js/foo.js');
$cache->clear($hash.'.url');
But that's a bit of a hack since this key is not documented and may change in the future.
Also you need to remember that the route $ttl
parameter not only triggers server cache but also client cache. Which means that you need to implement a cache buster to refresh the client cache. Something like assets/js/foo.js?v=3
.
You may consider implementing cache directly in your controller class. That would give you more flexibility.
I use this route:
GET|HEAD /assets/@folder/@type/v-@version/* = controllers\Assets->send, 3600
My controller:
namespace controllers;
class Assets {
private $paths;
private $types = ['css', 'js', 'i', 'fonts', 'files', 'icons'];
private $dontminify = ['i', 'fonts', 'files', 'icons'];
public function __construct() {
$this->fw = \Base::instance();
$this->paths['app'] = '../app/views/site_tpl/assets/';
$this->paths['core'] = '../core/views/default/assets/';
}
public function send() {
if (in_array($this->fw->get('PARAMS.folder'), array_keys($this->paths))
&& in_array($this->fw->get('PARAMS.type'), $this->types))
{
$folder = $this->paths[$this->fw->get('PARAMS.folder')];
$type = $this->fw->get('PARAMS.type');
if (in_array($type, $this->dontminify)) {
$file = $folder . $type . '/' . $this->fw->pop('PARAMS');
if (\Web::instance()->send($file)) {
return true;
}
} else {
$this->fw->set('UI', $folder . $type . '/');
$file = $this->fw->pop('PARAMS');
if (file_exists($this->fw->get('UI') . $file)) {
if (!$this->fw->exists('GET.dontminify')) {
echo \Web::instance()->minify($file);
return true;
} elseif (\Web::instance()->send($this->fw->get('UI') . $file)) {
return true;
}
}
}
}
$this->fw->error(404);
}
}
So, when I want to update version of file, I write somethong like this:
<script src="/assets/app/js/v-20160205/main.js"></script>