⚡ Simple Cache Class
This is a simple Cache Abstraction Layer for PHP >= 7.0 that provides a simple interaction with your cache-server. You can define the Adapter / Serializer in the "constructor" or the class will auto-detect you server-cache in this order:
- Memcached / Memcache
- Redis
- Xcache
- APC / APCu
- OpCache (via PHP-files)
- Static-PHP-Cache
Get "Simple Cache"
You can download it from here, or require it using composer.
{
"require": {
"voku/simple-cache": "3.*"
}
}
Install via "composer require"
composer require voku/simple-cache
composer require predis/predis # if you will use redis as cache, then add predis
Quick Start
use voku\cache\Cache;
require_once 'composer/autoload.php';
$cache = new Cache();
$ttl = 3600; // 60s * 60 = 1h
$cache->setItem('foo', 'bar', $ttl);
$bar = $cache->getItem('foo');
Usage
use voku\cache\Cache;
$cache = new Cache();
if ($cache->getCacheIsReady() === true && $cache->existsItem('foo')) {
return $cache->getItem('foo');
} else {
$bar = someSpecialFunctionsWithAReturnValue();
$cache->setItem('foo', $bar);
return $bar;
}
If you have an heavy task e.g. a really-big-loop, then you can also use static-cache. But keep in mind, that this will be stored into PHP (it needs more memory).
use voku\cache\Cache;
$cache = new Cache();
if ($cache->getCacheIsReady() === true && $cache->existsItem('foo')) {
for ($i = 0; $i <= 100000; $i++) {
echo $this->cache->getItem('foo', 3); // use also static-php-cache, when we hit the cache 3-times
}
return $cache->getItem('foo');
} else {
$bar = someSpecialFunctionsWithAReturnValue();
$cache->setItem('foo', $bar);
return $bar;
}
PS: By default, the static cache is also used by >= 10 cache hits. But you can configure this behavior via $cache->setStaticCacheHitCounter(INT).
No-Cache for the admin or a specific ip-address
If you use the parameter "$checkForUser" (=== true) in the constructor, then the cache isn't used for the admin-session.
-> You can also overwrite the check for the user, if you add a global function named "checkForDev()".