1

I have the following settings for custom provider

services.yaml

app.my_custom_redis_provider:
        class: Predis\Client
        factory: [ 'Symfony\Component\Cache\Adapter\RedisAdapter', 'createConnection' ]
        arguments:
            - '%env(REDIS_URL)%'
            - { retry_interval: 2, timeout: 10 }

cache.yaml

framework:
    cache:
        pools:
            cache.my_redis:
                adapter: cache.adapter.redis
                provider: app.my_custom_redis_provider

I am not sure how to use that in my controller class as a service. When I do like this, it doesn't work

    /**
     * @Route("/predis/client", name="test_redis_client")
     */
    public function testRedisClient(Predis\Client $cache)
    {
    }

When I map it to a class, it doesn't work either

<?php

namespace App\Client;

use Predis\Client;

class MyCustomRedisProvider
{
    public function __construct(Client $client){

    }
}

services.yaml

redis_cache:
        class: App\Client\MyCustomRedisProvider
        arguments: ['@app.my_custom_redis_provider']

THE WAY ONLY WORKS

However, when I use it plainly inside a Controller function it works

$client = RedisAdapter::createConnection(
                $this->getParameter('redis_url'),
                [
                    'persistent' => 1,
                    'timeout' => 20,
                    'ssl' => true
                ]
            );

But I don't wanna do like above.

Do I need an extra class to map it on services to use the custom provider?

mehmetsen80
  • 727
  • 1
  • 8
  • 25

1 Answers1

1

If configured (*.yaml) correctly, all available cache-polls are autowired and autoconfigured automatically.

Just run

bin/console debug:autowiring pool

or more precisely

bin/console debug:autowiring my_redis

and you'll get a list of all cache-polls as injectable services So in your case, you should see something like:

\Psr\Cache\CacheItemPoolInterface $cacheMyRedis (cache.my_redis)
\Symfony\Contracts\Cache\CacheInterface $cacheMyRedis (cache.my_redis)

Please note: there could be many with same variable name ($cacheMyRedis)

You can now use those in your controllers/actions and custom services.

For Example, in a controller action:


 // Example with Psr\Cache\CacheItemPoolInterface and some repository (e.g. UserRepository)
public function someAction(Request $request, Psr\Cache\CacheItemPoolInterface $cacheMyRedis, UserRepository $usersRepo)
{
    /** @var Psr\Cache\CacheItemInterface $cachedDataItem */
    $cachedDataItem = $cacheMyRedis->getItem('you_cache_key'); // it coukd be a hit / it could be a miss

    // get the real value
    $userData = $cachedDataItem->get();

    // got nothing?
    if (false === $cachedDataItem->isHit())
    {
        // get real data from DB and save it to cache, so next ->getItem('you_cache_key') will be "a hit"
        $userData = $usersRepo->findOneBy([ 'your_criteria']);
        if( $userData !== null )
        {
            $cachedDataItem->save($cachedDataItem->set($userData));
        }
    }
}

Example with Symfony\Contracts\Cache\CacheInterface $cacheMyRedis

public function otherAction(Request $request, \Symfony\Contracts\Cache\CacheInterface $cacheMyRedis, UserRepository $usersRepo)
{
    // caching with symfony contract works a bit different.
    // If it's a miss, callback will be executed and return value will be auto-save in cache with 'you_cache_key'
    // so next time you'll get value from cache.
    $userData = $cacheMyRedis->get('you_cache_key', function(ItemInterface $item) use ($usersRepo) {
        // $item->expiresAfter(600); // e.g. expires after 10 min
        // get real data from DB and return it on order to "save into cache"
        return $usersRepo->findOneBy([ 'your_criteria' ]);
    });
}

docs:

V-Light
  • 3,065
  • 3
  • 25
  • 31
  • Thank you but when I run RedisAdapter::createConnection() from code and $cacheMyRedis from as variable, they don't get the same item even though they both use the same Elasticache Redis endpoint? – mehmetsen80 Nov 10 '22 at 18:34
  • @mehmetsen80 what do you mean "don't get the same item" ? So `$cacheMyRedis->get('my_cache_key')` results differs from `$client->get('my_cache_key')` ? If so, how? – V-Light Nov 11 '22 at 09:20
  • Exactly, they are supposed to get the same item from Elasticache but they act as their own – mehmetsen80 Nov 12 '22 at 16:00
  • Try to `dump($cacheMyRedis)` and `dump($client)` and dig around a bit. I'd say it's a config issue. Maybe wrong DSN? Also inspect your `?cache` panel in `/_profiler/` – V-Light Nov 13 '22 at 11:57