spiral / framework

High-Performance PHP Framework
https://spiral.dev
MIT License
1.82k stars 89 forks source link

CacheManager ability to set custom cache storage. #1142

Open gam6itko opened 2 months ago

gam6itko commented 2 months ago
Q A
Bugfix?
Breaks BC?
New feature? ✔️
Issues #...
Docs PR spiral/docs#...

User can set custom cache in bootloader.

Example for redis

use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Boot\EnvironmentInterface;
use Spiral\Cache\CacheStorageRegistryInterface;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Psr16Cache;

final class RedisCacheBootloader extends Bootloader
{
    public function boot(CacheStorageRegistryInterface $cacheRegistry, EnvironmentInterface $env): void
    {
        $cacheRegistry->set(
            name: 'redis',
            cache: new Psr16Cache(
                pool: new RedisAdapter(
                    redis: RedisAdapter::createConnection($env->get('REDIS_DSN'))
                ),
            )
        );
    }
}

For now my cache config not looks pretty.

return [
    'default' => env('CACHE_STORAGE', 'redis'),

    'storages' => [
        'redis' => [
            'type' => Psr16Cache::class,
            'pool' => new Autowire(
                alias: RedisAdapter::class,
                parameters: [
                    'redis' => RedisAdapter::createConnection(env('REDIS_DSN')),
                ],
            ),
        ],
    ],
];