CakePHP Tips: Disable Database Caching

Cake caches database queries. This is good, generally, it speeds things up a lot. But it is not always good. For example, if I want to query the database once a second to look for updates (e.g. for my chat application) the you don’t want the cache. Here’s how to clear it:

1) Create /app/app_model.php, and add in it the following

<?php

class AppModel extends Model{
function _clearDBCache() {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->_queryCache = array();
}
}

Note: you don’t always need a close "?>"

2) Call $modelNameHere->_clearDBCache() whereever you need the DB cache cleared.

That’s it! Have fun!

Whilst I am on the subject of CakePHP tips, why not look into using expects() to make your CakePHP queries more efficient – only request the data you need. Much better than using unbindModel and bindModel all over the place!

Bookmark and Share

5 Responses to “CakePHP Tips: Disable Database Caching”

  1. Dmitry Says:

    Thank you! Very useful.

  2. Sarah Says:

    Took me a while to work out that the database caching was the issue – it’s quite something isn’t it?!

    Then it was a quick Google and I found your suggestion.

    Thanks :)

  3. Patrick-Oliver Says:

    $this->Model->cacheQueries = false;
    Should work, too.

  4. Subramanian Says:

    But my assignment requires me to update the records if the entry already exists or insert it if there is no such entry during a bulk insert.
    Could you suggest a solution for that.

  5. Benjie Says:

    Subramanian: Model::save does this for you – if your data has an id entry then it updates the vales with that id entry, otherwise it creates a new entry with the data you have given. Hope this helps?

Leave a Reply