thesearentthedroids
thesearentthedroids

Reputation: 620

API caching with Symfony2

How can I cache my API responses built with Symfony?

I started to dig into FosCacheBundle and the SymfonyHttpCache, but I'm not sure about my usecase.

You can only access the API with a token in header and every users get the same data in their response for the same URL called (and with the same GET parameters).

I would like to have a cache entry for each of my URL (including get parameters) and also, is it possible to reorder my GET parameters before the request is processed by my cache system (so that the system dont create multiple cache entries for "URL?foo=bar&foz=baz" and "URL?foz=baz&foo=bar" which returns the same data)

Upvotes: 0

Views: 224

Answers (1)

Putr
Putr

Reputation: 967

Well there are multiple ways.

But the simplest is this:

If the biggest problem is database access than just caching the compiled result in memcache or similar will go a long way. Plus, this way you stick to your already working authentication.

In your current controller action, after authentication and before payload creation check if there's an entry in memchache. If no, build the payload and save it into memcache than return it. When next request comes along there will be no DB access as it will be returned from memcache. Just don't forget to refresh the cache how ever often you need.

Note: "Early optimization is the root of all evil" and "Servers are cheaper than programmer hours" are to things to keep in mind. Don't complicate your life with really advanced caching methods if you don't need to.

Upvotes: 1

Related Questions