Documentation
Cache
- Migration : How to upgrade from Temma 1.x to version 2
- Installation : Download Temma and install it to start your web project
- Configuration : All the configuration directives of the etc/temma.json file and the optional environment variables
- Routing : Temma's default routing system, and advanced routing
- Log : Use of the log system, management by criticality levels
- Controllers : Essential parts of your web application
- Views : Smarty templates or JSON/CSV/RSS/iCal/INI exports
- Dependencies injection : The backbone of your application developments
- Sessions : Extension of user sessions managed by PHP
- Cache : So as not to redo the same calculations several times
- Model : How to use DAOs to access databases
- Plugins : How to create your own plugins, and a list of plugins offered by Temma
- Execution flow : How to manage the execution flow, between plugins and the controller
- Helpers : Items offered by Temma to help you in various circumstances
Presentation
The cache is usually used to store information that is often accessed for reading. It is therefore preferable not to read them in the database on each access, but rather to aggregate them and place them in cache; subsequent readings will be faster.
It should be understood that, unlike sessions, cache variables are common to the entire application.
It is therefore important to think carefully about the naming of variables, in order to be able to find them easily.
Another difference is that the purpose of the cache variables is to remain temporary. They expire after a certain time,
which can be defined globally or precisely for each variable. By default, the expiration time is 24 hours.
Temma automatically creates the cache management object, if the configuration is set up for it.
In controllers the connection to the cache is available by writing:
$this->cache
In the other objects managed by the dependency injection component, the connection to the cache can be accessed by writing:
$this->_loader->dataSources['cache']
Writing data
To create or modify a cache variable, just use the object as an associative array:
$this->cache['myVariable'] = $value;
If the value assigned to the variable is null, the variable is deleted from the session.
It is possible to write a cache variable giving it a maximum lifetime, thanks to the set() method.
It takes as parameter the name of the variable, its value, and the caching time in seconds.
Here is an example of use:
// the data will remain in cache for 1 hour
$this->cache->set('myVariable', $value, 3600);
This method returns the old value of the variable (if it existed, otherwise it returns null).
Deleting data
To destroy a cache variable:
unset($this->cache['myVariable']);
Reading data
To read data from the cache, just use the object as an associative array:
$user = $this->cache['user:12'];
With the get() method, it is also possible to read a cache variable and, if it does not exist, execute an anonymous function, the return value of which will be stored in the cache (under the requested name) and finally returned:
$userId = 12;
$user = $this->cache->get("user:$userId", function () use ($userId) {
$sql = "SELECT * FROM Users WHERE id = '$userId'";
$user = $this->db->queryOne($sql);
return ($user);
});
In the example above, we are trying to retrieve information about a user from the cache. If the cache already contains the data, we retrieve them directly. If, on the other hand, the data is not present in the cache, the anonymous function is executed. This makes a request on the database in order to retrieve information about the user; the function returns this information, which is automatically cached, and returned by the get() method.
As with the set() method, it is possible to provide a maximum lifetime for caching:
// the data will be stored in cache for 5 minutes
$var = $this->cache->get('myVariable', function () {
return ('some value');
}, 300);
Cache expiration
The setExpiration() method is used to set the default caching time. This avoids having to define it
explicitly each time a data is written in cache.
It takes one parameter, which is the maximum lifetime of cached data, expressed in seconds. By default, the duration is 86400 seconds (24 hours).
This method returns the instance of the cache object.
// set the default expiration delay to one hour
$this->cache->setExpiration(3600);
// expiration of 5 minutes, followed by addition of data
$this->cache->setExpiration(300)->set('aa', 'bb');
You can use the getExpiration() method to find out the currently configured caching time.
// we want to ensure that the expiration delay is at least 1 hour
$exp = $this->cache->getExpiration();
if ($exp < 3600)
$this->cache->setExpiration(3600);
Prefix management
What we call "prefixes" is a label that is appended to the names of cache variables. Their interest is to be able to manage all the cache variables having the same prefix, to invalidate them in a single operation.
The setPrefix([string $prefix])
method is used to define the prefix of the variables that
will be processed during the get() and set() calls that will follow.
Calling it without parameters removes the use of prefixes.
It returns the instance of the cache object.
The clear(string $prefix)
method is used to invalidate all the cache variables which have
the prefix passed as a parameter.
It also returns the instance of the cache object.
Example of use:
// definition of a prefix
$this->cache->setPrefix('sites');
// add cache variables
$this->cache->set('A', $siteA);
$this->cache->set('B', $siteB);
$this->cache->set('C', $siteC);
// definition of another prefix
$this->cache->setPrefix('articles');
// add cache variables
$this->cache->set('Y', $articleY);
$this->cache->set('Z', $articleZ);
// delete the variables belonging to the first prefix
// ("A", "B" et "C")
$this->cache->clear('sites');
// stop using the "articles" prefix
$this->cache->setPrefix();
// retrieve a prefixed variable
$data = $this->cache->setPrefix('articles')->get('Z');
It is possible to know the current prefix thanks to the getPrefix() method:
$prefix = $this->cache->getPrefix();
if ($prefix != 'sites')
$this->cache->setPrefix('sites');
Enabling / disabling cache
The disable() method is used to temporarily disable the use of the cache. All subsequent calls
will not return an error, but no cache access will be performed.
The enable() method allows you to re-enable the use of the cache (after a call to disable(), for example).
These two methods return the instance of the cache object.
Example of use:
// deactivate the cache
$this->cache->disable();
// the anonymous function will be systematically executed,
// because the cache is disabled
$article = $this->cache->get(
"article:$articleId",
function () use ($articleId, $dao) {
return ($dao->get($articleId));
}
);
// reactivate the cache and save a variable
$this->_cache->enable()->set('name', $value);
The enable() method re-enables the cache that has been temporarily disabled. It also returns the instance of the cache object.
$this->cache->enable();
To find out if the cache is enabled or disabled, you can use the isEnabled() method, which returns true if the cache is enabled, and false otherwise.
if (!$this->cache->isEnabled())
print("Cache disabled");
Previous: | Sessions |
Next: | Model |
Table of Contents
- Migration : How to upgrade from Temma 1.x to version 2
- Installation : Download Temma and install it to start your web project
- Configuration : All the configuration directives of the etc/temma.json file and the optional environment variables
- Routing : Temma's default routing system, and advanced routing
- Log : Use of the log system, management by criticality levels
- Controllers : Essential parts of your web application
- Views : Smarty templates or JSON/CSV/RSS/iCal/INI exports
- Dependencies injection : The backbone of your application developments
- Sessions : Extension of user sessions managed by PHP
- Cache : So as not to redo the same calculations several times
- Model : How to use DAOs to access databases
- Plugins : How to create your own plugins, and a list of plugins offered by Temma
- Execution flow : How to manage the execution flow, between plugins and the controller
- Helpers : Items offered by Temma to help you in various circumstances