mirror of
https://github.com/shlinkio/shlink.git
synced 2026-03-12 01:54:41 +08:00
Enhanced CacheFactory to support redis and allow optional APCu
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user