Chad 2010-06-17
The sfDoctinePlugin itself encapsulated a class for manipulating the PECL Memcache module1.
With it, we can connect to any cache server that installed Memcached ( a daemon in Linux, my colleague Kim told me that there's also a Windows version2.)
- // configuration.calss.php
- public function configureDoctrine(Doctrine_Manager $manager)
- {
- // ...
- $servers = array(
- 'host' => sfConfig::get('app_memcached_server_host'),
- 'port' => sfConfig::get('app_memcached_server_port'),
- 'persistent' => true
- );
- $option = array(
- 'servers' => $servers,
- 'compression' => false
- );
- $cacheDriver = new Doctrine_Cache_Memcache($option);
- $manager->setAttribute(Doctrine::ATTR_RESULT_CACHE, $cacheDriver);
- // ...
Then we can use it to cache data:
- // try to get from cache
- $manager = Doctrine_Manager::getInstance();
- $cacheDriver = $manager->getAttribute(Doctrine::ATTR_RESULT_CACHE);
- # method 1
- $aryVehicleUrls = $cacheDriver->fetch('vehicle_urls');
- if(!$aryVehicleUrls){
- $aryVehicleUrls = array();
- }
- if(isset($aryVehicleUrls[$v['id']])){
- return $aryVehicleUrls[$v['id']];
- }
- // not found in cache, get data
- // ...
- // cache it
- $aryVehicleUrls[$v['id']] = $slug;
- $cacheDriver->save('vehicle_urls',$aryVehicleUrls,null,true);
But then I found that it became very slow ( much slower than without cache)!!
I couldn't figure out why this would happen, then I try to change the way to store the data, from putting a lot of records into one array and then cache it, to directly cache the records individually:
- // ...
- # method 2
- $vehicleUrl = $cacheDriver->fetch('vehicle_url_'.$v['id']);
- if($vehicleUrl){
- return $vehicleUrl;
- }
- // not found in cache, get data
- //...
- // cache it
- $cacheDriver->save('vehicle_url_'.$v['id'],$slug,null,true);
Now this works much faster, even faster than without cache (which is supposed to be...), though it's still slow when it do the first run, which means to save the data into cache.
Below are the figures I tested out:
So, it seems that it's not a good idea to store data with complicated structure into Memcache. If you are going to cache a lot of records, it's better to give each record a cache key and cache them directly.
1. PECL Memcache module, http://pecl.php.net/package/memcache
2. Memcached for Windows, http://jehiah.cz/projects/memcached-win32/files/memcached-1.2.1-win32.zip