3d01196b0a41950cedd4a26bd5bb49301db49dc8
IQParts Cache
PHP Cache library with namespace, filesystem and (p)redis implementations.
Requirements
Requires PHP 7.0+. Older versions might work but have not been tested.
Installation
composer require iqparts/cache
Another cache library
This cache library has been highly inspired by Genkgo.Cache. We recommend using Genkgo's library as it implements more adapters. The reason for this library was the need to have a backup for redis which still was able to store cached values with a variable TTL.
Code
This library attempts to comply with PSR-1, PSR-2 & PSR-4.
Create your own adapter
Create an adapter that implements CacheAdapterInterface. Take the MemoryAdapter as example:
<?php
declare(strict_types=1);
namespace IQParts\Cache\Adapter;
final class MemoryAdapter implements CacheAdapterInterface
{
/**
* @var array
*/
private $data = [];
/**
* @var array
*/
private $timeToLive = [];
/**
* @param string $key
* @return mixed
*/
public function get(string $key)
{
if (!isset($this->data[$key])) {
return null;
}
if (!isset($this->timeToLive[$key])) {
return $this->data[$key];
}
if ($this->ttl($key) > 0) {
return $this->data[$key];
}
unset($this->timeToLive[$key]);
unset($this->data[$key]);
return null;
}
/**
* @param string $key
* @param $value
* @param int|null $ttl
* @return void
*/
public function set(string $key, $value, int $ttl = null)
{
$this->data[$key] = $value;
if ($ttl !== null) {
$this->timeToLive[$key] = time() + $ttl;
}
}
/**
* @param string $key
* @return mixed
*/
public function delete(string $key)
{
unset($this->data[$key]);
unset($this->timeToLive[$key]);
return 1;
}
/**
* @param string $key
* @return mixed
*/
public function keys($key = '*')
{
$matches = [];
foreach ($this->data as $name => $value) {
if (fnmatch($key, $name)) {
$matches[] = $name;
}
}
return $matches;
}
/**
* @param $key
* @return int
*/
public function ttl($key): int
{
if (isset($this->timeToLive[$key])) {
return max($this->timeToLive[$key] - time(), 0);
}
return self::NO_TTL;
}
}
Multiple Adapters
Adapters can be queued. Example:
$cache = new NamespaceAdapter(
'my-namespace:',
new MemoryAdapter()
);
/**
* This will result in 'my-namespace:my-key'
* set to 'my-value'
*/
$cache->set('my-key', 'my-value');
Description
Languages
PHP
100%


