Enhanced CacheFactory to support redis and allow optional APCu

This commit is contained in:
Alejandro Celaya
2019-08-10 17:44:09 +02:00
parent c9be89647c
commit 16653d60ed
3 changed files with 119 additions and 41 deletions

View File

@@ -4,22 +4,48 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Common\Cache;
use Doctrine\Common\Cache;
use Interop\Container\ContainerInterface;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Zend\ServiceManager\Factory\FactoryInterface;
use Predis\Client as PredisClient;
use Psr\Container\ContainerInterface;
use function Shlinkio\Shlink\Common\env;
use function extension_loaded;
class CacheFactory implements FactoryInterface
class CacheFactory
{
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null): Cache\Cache
{
// TODO Make use of the redis cache via RedisFactory when possible
/** @var callable|null */
private $apcuEnabled;
$appOptions = $container->get(AppOptions::class);
$adapter = env('APP_ENV', 'pro') === 'pro' ? new Cache\ApcuCache() : new Cache\ArrayCache();
$adapter->setNamespace((string) $appOptions);
public function __construct(?callable $apcuEnabled = null)
{
$this->apcuEnabled = $apcuEnabled ?? function () {
return extension_loaded('apcu');
};
}
public function __invoke(ContainerInterface $container): Cache\CacheProvider
{
$config = $container->get('config');
$adapter = $this->buildAdapter($config, $container);
$adapter->setNamespace($config['cache']['namespace'] ?? '');
return $adapter;
}
private function buildAdapter(array $config, ContainerInterface $container): Cache\CacheProvider
{
$isDebug = (bool) ($config['debug'] ?? false);
$redisConfig = $config['cache']['redis'] ?? null;
$apcuEnabled = ($this->apcuEnabled)();
if ($isDebug || (! $apcuEnabled && $redisConfig === null)) {
return new Cache\ArrayCache();
}
if ($redisConfig === null) {
return new Cache\ApcuCache();
}
/** @var PredisClient $predis */
$predis = $container->get(RedisFactory::SERVICE_NAME);
return new Cache\PredisCache($predis);
}
}