In this week I have been working on increasing a project home page performance.
and am using cakephp cache to cache query individually using find method.
but i made a function in app model witch can deal with mySql -native- query cache.
and here how you can do this:
place the following function within your app/app_model.php.
function nativeQuery($query,$Cache= false,$QryKey=null,$QryExpires=null){
if(isset($query) && !empty($query) && is_string($query)){
if($Cache != false && isset($QryKey) && !is_null($QryKey)){
$key = $QryKey;
$expires = ‘+1 hour’;
if (isset($QryExpires) && !is_null($QryExpires) ) {
$expires=$QryExpires;
}
// cache settings
Cache::config(‘sql_cache’, array(
‘prefix’ => strtolower($this->name) .’-',
‘duration’ => $expires
));
// read result from cache
$results = Cache::read($key, ‘sql_cache’);
if (!is_array($results)) {
$results = $this->query($query);
Cache::write($key, $results, ‘sql_cache’);
}
return $results;
}else{
//NON-CHACHED QUERY
$result=$this->query($query);
return $result;
}
}else{
// no query available
return false;
}
}
then create a folder called sql within your tmp/cache/ and chmod the permissions to 777.
then open up your app/config/core.php file and place the following code
Cache::config('sql_cache', array( 'engine' => 'File', 'path' => CACHE .'sql'. DS, 'serialize' => true, )); and then we are ready to use our custom method like this: $query='select * from posts'; $result=$this->ModelNmae->nativeQuery($query,true,'keyName','+1 hour');
you can clear the cache using Cache::delete() method or delete the file from the cache folder
here how i do this
hope its helpful…
refrences:
- http://www.milesj.me/blog/read/34/cacheing-each-query-individually
- http://www.endyourif.com/caching-queries-in-cakephp/
- http://jamienay.com/2009/11/adding-automatic-caching-to-model-find-in-cakephp-1-2/






[...] the original: Cakephp cache query « Islam khalil's Blog If you enjoyed this article please consider sharing [...]
Hi,
Just to say that I get an error here.
When I call this ‘nativeQuery’, cakephp tries to execute a SQL query that is exactly the name of the function and ignores the SQL query I put in the query arg.
I mean, it seems that I call a normal query like $this->Model->query(‘nativeQuery’), which obviously give an error.
I checked on the SQL debug and it shows a SQL command to ‘nativeQuery’, which does not exist.
[...] Cakephp cache query March 2010 1 comment and 1 Like on WordPress.com, 3 [...]