Zend Framework 2: Caching Using Event Manager

Caching is a great way of storing and returning data from a temporary store without having to do necessary business logic to fetch the data after it’s already been fetched once. Basically, the data is retrieved once and stored temporarily “somewhere”, whether, it be a file system, database, memory, for a specific amount of time. The next time the same page is loaded, the data has already been retrieved and can therefore be pulled out of temporary storage without having to do the computation all over again. This is particularly useful in applications that receive a lot of traffic, therefore, hammering the server with lots of requests.

Zend Framework 2 provides a number of ways to deal with caching out of the box via configuration. A handy concept is to catch a request through the MvcEvent::EVENT_ROUTE with a negative priority, check if what’s being requested exists in the cache. Should the item exist, return a response, otherwise, allow the application to continue and finish rendering via the controller. If the application reaches the controller, listen into the MvcEvent::EVENT_RENDER event and inject some data into the cache.

A friend of mine, Shenghua, has written a blog post about the implementation of how to use the ZF2 event manager to store and retrieve data from the cache. Check out his blog post https://github.com/shenghuahe/zf2-cache-mvc-response

Leave a comment