Caching Database Data
1Introduction
This mini-tutorial aims to cache data retrieved from a database.
We'll assume that you already have a website based on Temma, with a controller that displays data from a relational database.
2Configuration
In the configuration file, we'll add a data source corresponding to a Memcache server.
Edit the etc/temma.php file:
<?php
return [
'application' => [
'dataSources' => [
'db' => 'mysql://user:pwd@localhost/base',
'cache' => 'memcache://localhost',
],
],
];
- Line 6: Defines the data source connected to a MySQL database.
- Line 7: Defines the data source connected to a Memcache server.
3Controller
Let’s imagine a very simple controller that displays a list of users.
Here’s an example implementation:
<?php
/** User controller. */
class User extends \Temma\Web\Controller {
/** Action that displays the list of users. */
public function list() {
// fetch the list from the database
$users = $this->_loader->UserDao->search();
// store the list in a template variable
$this['users'] = $users;
}
}
Each time the list action is accessed, a query is executed on the database via the UserDao object.
Now let's see how we can add caching to avoid querying the database every time:
<?php
/** User controller. */
class User extends \Temma\Web\Controller {
/** Action that displays the list of users. */
public function list() {
// define the cache key
$cacheVarName = 'user:list';
// fetch the list from the cache
$users = $this->cache->get($cacheVarName, function() {
// this code runs if the value is not cached
// fetch the list from the database
return $this->_loader->UserDao->search();
});
// store the list in a template variable
$this['users'] = $users;
}
}
All related information is available in the cache documentation.