Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ashitvora's avatar

What is the best place to Cache the data?

In one of my apps I've to make dozens of call to third party application to get the exact data I want and it also limits the number of api requests I can make.

To overcome the delayed response and api throttle problem, I wish to cache the data.

What is the best place to cache the data - Controller or the Service that fetches the data?

At the moment it feels like it should be cached in the Controller since the data I need to generate unique key is in controller and is not being passed to the service. But wondering if Controller should have knowledge about caching stuff. Or should I add one more layer in between Controller and Service which does the caching and forward the request to Service only when there is Cache miss.

0 likes
3 replies
ChristophAust's avatar

I once realized it using an own class for caching. Not sure if this is the best way though. Then my controller checked if there is a key to return it or to get the data from the service. If you use repository pattern I would let the repository handle it.

simondavies's avatar

if its not too much code a line or two then in the controller is fine, else if your controller starts to do some business type things then port to a repository etc and then do your work in there as well as the cache. I tend to put the cache side on the repository as it then caches all the work and stuff i need or if its a controller calling a simple DB all etc then tis added to the controller.

amitwebdev's avatar

@simondavies doing cache in the service layer the best place or not? like we can change our repository layer in the future. and I still have a question which is the best place to do cache? sorry, maybe a lack experience I not getting a conclusion about cache on your statement. the

Please or to participate in this conversation.