Zend Cache Quick and Easy
Created: Last updated:
I bet you have data you query from a database or another source that rarely changes and even then you can live with it for, lets say, 24 hours. If so, you might want to think about the Zend_Cache class. Especially for cases like this there is a particular quick and easy way to setup and implement Zend_Cache for caching small chunks of data you use over and over again.
Quick and easy
Where you place this method is up to you and if you implement this setup for Zend_Cache as a static method (like I will demonstrate in this tutorial) is also up to you.
It seems that people have some difficulties with Zend_Cache because they have to deal with the fact that we have to provide a frontend and a backend. As long as you don't want to implement crazy stuff you can create a simple method that does great things for you. For our simple method we need to worry about and provide only three things:
Core - Frontend
First off, the Core in the frontend. Don't bother about what the Core is or does; it's just what you need to get started. If you look at the Zend_Cache_Core documentation you will find the sentence " It is a generic cache frontend and is extended by other classes." Nuff said, I think.
File - Backend
Second we have File for the backend which simply means that we want to save the data into a file. To make this work you have to provide a filepath for a directory where the cache files will reside.
Lifetime
The lifetime simply means how long the data is valid. The value is in second, i.e. 60 is a minute, 3600 an hour and so on.
The Code
Now that we have all the information here is the code how you can craft your method in bare minimum. My method actually has a few more things in it but that would not be quick and easy anymore.
- public static function initializeCache(
- $lifetime = 3600, $frontend = 'Core', $backend = 'File)
- {
- $cache_dir = '/path/to/your/local/cache/directory'
- $automatic_serialization = true;
- $frontendOptions = compact('lifetime', 'automatic_serialization');
- $backendOptions = compact('cache_dir');
- return Zend_Cache::factory(
- $frontend,$backend,$frontendOptions,$backendOptions);
- }
Now all you have to do is get the object and you can save and load data to the cache object. Quick and easy.
- $cache = MyClass::initializeCache(60);
- $cache_id = 'data1';
- $data1 = $cache->load($cache_id);
- if (empty($data1)) {
- $data1 = array(1=>'my data'); // usually this would be your DB method
- $cache->save($data1,$cache_id);
- // next time (within 60 seconds) the data will come from the cache
- }
Once you have the object you can do a lot of other things but for the quick and easy part that is all you need for caching with Zend_Cache. Hope you like it.