Database Caching Class
The Database Caching Class contains functions that permit you to cache your queries.
Important: This class is initialized automatically by the database driver when caching is enabled. Do NOT load this class manually. More info below...
How Does Caching Work?
When caching is enabled, anytime a "read" type query (SELECT) is run, the result object will be serialized and stored in a text file on your server. Subsequent calls to that query will use the result from the cache file rather then accessing your database. In other words, the first time a page is loaded a cache file will be written. The next time the page is loaded the cached file will be used.
When a "write" type query (INSERT, UPDATE, etc.) is run , any cache files associated with the particular page being viewed will be deleted automatically. If you need to update some data with every page load (user stats, for example) you will need to manually disable caching just before running your "write" query, then re-enable it just after. Otherwise, your site will be caught in a cycle of writing/deleting caches with every page view, creating more load then if you were not using caching. More information on this will be found below.
Although caching will reduce your database load, dealing with cache files does generate more up-front processing and file-system operations, as cache files are created and read. Instead of accessing your database for information text files are used.
Whether you see a performance gain as a result of caching is dependant on many factors. For example, if you have a highly optimized database under very little load, you probably won't see a performance boost. If your database is under heavy use you probably will see an improved response, assuming your filesystem is not overly taxed. In some clustered server environments caching may be detrimental since filesystem operations are so intense. On single servers (particularly in shared enironments) caching will probably be beneficial. Unfortunately there is no single answer to the question of whether you should cache your database. It really depends on your situation.
Enabling Caching
Enabling caching requires three steps:
- Creating a directory on your server where the cache files will be written.
- Setting the path to your cache folder in your application/config/database.php file.
- Enalbling the caching preference either in your database config file or manually in your controllers.
Caching Example
Here is an example showing how you can selectively cache some queries and not others. Notice that the "write" type queries
are not.
'>.$row->content.'
$this->db->cache_on(); // Turns on caching. We assume that you've set up a valid cache foler...
$query = $this->db->query("SELECT * FROM blog LIMIT 10);
foreach ($query->result() as $row)
{
echo '
'.$row->title.'
';
echo '