A
A
Alexey Anisimov2017-05-17 15:40:52
symfony
Alexey Anisimov, 2017-05-17 15:40:52

Symfony and Redis where to write the logic for getting the cache?

Good afternoon.
I am writing a project in symfony. There is a task to cache the results of some queries in redis.
Wrote a service for getting data from the cache and writing data to the cache using the RedisAdapter adapter from the Symfony/Cache component.
Where to write the logic of the form "if there is a cache, return the cache, otherwise from the database" (in the example, I stuffed the controller into the action)?

public function getUsersAction()
    {
        $redisHelper = $this->get('app.redis.helper');

        $cache = $redisHelper->getCache('users_list');

        if ($cache) {
            return $cache;
        }

        $users = $this->getDoctrine()->getRepository(User::class)->findAll();
        $redisHelper->setCache('users_list', $users);

        return $users;
    }

Options:
1. In the controller action
2. In the repository method (if here, how to inject your service there?)
3. Somewhere else
I want to understand how to do it right.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Pavlov, 2017-05-17
@AnisimovAM

Make a service, it has methods for obtaining data. In methods, access to the cache and repositories.
Ideally, the controller does not need repositories at all - all work with them is in this service.
In this service and invalidation is done.
Methods can be by a specific entity, or by type (getEntity($type, $id)) if convenient.
UPD. As a tool, I recommend using the Cache Component , it has the ability to use record tagging, it's very convenient (for invalidation)! Doctrine Cache is deprecated imho.

K
Konstantin B., 2017-05-17
@Kostik_1993

And let them trample me, but as for me, the deeper we dig in the logic of choosing from the cache or database, the less benefit it will bring us at all. Caching should be placed as close as possible to the request, the request received is in the cache, it was given, no, it went further. Therefore, in the controller, as it seems to me, it is the very place. The main thing is to write everything beautifully and do no harm.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question