Data source: Cache


1Présentation

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.

If you have correctly configured the connection parameters to the Memcached server, Temma automatically creates an object of type \Temma\Datasources\Memcache. By convention, we will assume that you have named this connection cache in the etc/temma.php file (see the configuration documentation).

In controllers the connection to the cache is then 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']

2Configuration

In the etc/temma.php file (see configuration documentation), you declare the DSN (Data Source Name) used to connect to the Memcache server(s).

When data is distributed across several Memcache servers, it's up to the clients to know which servers are which, and their list must be configured identically on all clients that need to connect to the servers.

The DSN for connecting to a Memcache server is written as: memcache://SERVEUR[:PORT]
The default port number is 11211.

When there are several Memcache servers, separate them with a semicolon.
Example: memcache://localhost;otherhost:11000;anotherhost

If the Memcache server is running on the same machine, it is possible to connect using a Unix socket, thus avoiding network latencies. In this case, the DSN is: memcache://CHEMIN:0
The path must lead to the Unix socket (often /var/run/memcached.sock).
The port number must be 0 (zero) by default.
Example: memcache:///var/run/memcached.sock:0


3Unified calls

3.1Array-like access

// verification of data existence
if (isset($this->cache['key1']))
    doSomething();

// data reading (deserialized)
$data = $this->cache['key1'];

// data writing (serialized)
$this->cache['key1'] = $value;

// data deletion
unset($this->cache['key1']);

// elements count
$nbr = count($this->cache);

3.2General methods

// verification of data existence
if ($this->cache->isSet('user:1'))
    doSomething();

// data deletion
$this->cache->remove('user:1');

// multiple data deletion
$this->cache->mRemove(['user:1', 'user:2', 'user:3']);

// prefix-based data deletion
$this->cache->clear('user:');

// delete all data
$this->cache->flush();

3.3Management of complex serialized data

Memcache does not support the search() method.

By default, data stored in Memcache has a lifetime of 24 hours. It is possible to specify the number of seconds of caching, up to 30 days (either by specifying 2592000 seconds, or by specifying a value of -1).

// data reading (deserialized)
$user = $this->cache->get('user:1');
// read data with default value
$color = $this->cache->get('color', 'blue');
// read data with data creation if necessary
$user = $this->cache->get("user:$userId", function() use ($userId) {
    return $this->dao->get($userId);
});

// read multiple data (deserialized)
$users = $this->cache->mGet(['user:1', 'user:2', 'user:3']);

// data writing (serialized)
$this->cache->set('user:1', $userData);
// write (serialized) data with a lifetime of one hour
$this->cache->set('user:1', $userData, 3600);

// multiple data writing (serialized)
$this->cache->mSet([
    'user:1' => $user1data,
    'user:2' => $user2data,
    'user:3' => $user3data,
]);
// multi-data writing, with a 30-day lifetime
$this->cache->mSet([
    'user:1' => $user1data,
    'user:2' => $user2data,
], -1);

3.4Raw data management

Memcache does not support the find() method.

By default, data stored in Memcache has a lifetime of 24 hours. It is possible to specify the number of seconds of caching, up to 30 days (either by specifying 2592000 seconds, or by specifying a value of -1).

// read data (raw)
$html = $this->cache->read('page:home');
// read data with default value
$html = $this->cache->read('page:home',
                           '<html><body><h1>Homepage</h1><body><html>');
// read data with data creation if necessary
$html = $this->cache->read('page:home', function() {
    return file_get_contents('/path/to/homepage.html');
});

// read multiple (raw) data
$pages = $this->cache->mRead(['page:home', 'page:admin', 'page:products']);

// copy data to a local file
$this->cache->copyFrom('page:home', '/path/to/newpage.html');
// copy data to local file, with default value
$this->cache->copyFrom('page:home', '/path/to/newpage.html', $defaultHtml);
// copy data to a local file, with data creation if necessary
$this->cache->copyFrom('page:home', '/path/to/newpage.html', function() {
    return file_get_contents('/path/to/oldpage.html');
});
// copy data to a local file, with data creation if necessary
// (with a lifetime of one hour)
$this->cache->copyFrom('page:home', '/path/to/newpage.html', function() {
    return file_get_contents('/path/to/oldpage.html');
}, 3600);

// write (raw) data
$this->cache->write('color:blue', '#0000ff');
// data writing (raw) with a lifetime of one hour
$this->cache->write('color:blue', '#0000ff', 3600);

// write multiple (raw) data
$this->cache->mWrite({
    'color:blue'  => '#0000ff',
    'color:red'   => '#ff0000',
    'color:green' => '#00ff00',
]);
// write multiple data with a 30-day lifetime
$this->cache->mWrite({
    'color:blue'  => '#0000ff',
    'color:red'   => '#ff0000',
], -1);

// write (raw) data from a local file
$this->cache->copyTo('page:home', '/path/to/homepage.html');
// write data from a local file, with a lifetime of one hour
$this->cache->copyTo('page:home', '/path/to/homepage.html', 3600);

// write multiple (raw) data from local files
$this->cache->mCopyTo([
    'page:home'     => '/path/to/homepage.html',
    'page:admin'    => '/path/to/admin.html',
    'page:products' => '/path/to/products.html',
]);
// write multiple data from local files with a 30-day lifetime
$this->cache->mCopyTo([
    'page:home'  => '/path/to/homepage.html',
    'page:admin' => '/path/to/admin.html',
], -1);

4Specific calls

4.1Cache 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);

4.2Prefix 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');

4.3Enabling / 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");