Elxis cache

Last update by Elxis Team

How to use the Elxis file cache library on your own projects and for custom purposes.

Elxis handles automatically file cache on modules where the cache parameter has been set to 1 (enabled). Module caching leads to saving the HTML output of the module into the repository/cache/ folder for later usage. But what about other type of extensions or custom actions inside a module or a plugin? With the elxisCache library you can save into cache and retrieve from it easily any data block your application may need. In this article we will show you how to work with the elxisCache library.

Workcase scenario

Let's say you are up to develop a module or a plugin that needs to connect to a remote host and retrieve some data (an XML file for example). If these data dont change frequently is it very bad to connect on the remote host on each user request (click). Remote connections are slow. We need to download this file once, save it in cache for some time and when a time limit has reached refresh the cache by fetching a new version of the file from the remote host. This is a typical example in which cache should always be used. You can also use cache (or Elxis APC) on any task even if no remote connection takes place. Take CPU expensive tasks as example. This depends on your project of course and what you want to do.


Get cache instance

To get/initiate Elxis cache library is simple, just call the getCache method of Elxis factory.

$eCache = eFactory::getCache();

elxisCache methods

Public methods of the elxisCache library.

begin

Starts a new caching process. Returns cached item state (integer).

public function begin($element, $id, $group='', $cachetime=0, $mlang=true, $force=false, $extension='php')
  • (string) element A name for the cached file specific to the element it contains data for. It can be any string.
  • (string) id An ID string to separate the file from others of the same element. It can be any string.
  • (string) group The name of the folder inside the repository/cache/ directory in which you want to save the cached file. Leave empty to save it inside cache folder root. If the folder doesn't exist elxisCache will try to create it.
  • (int) cachetime The life time in seconds of the cached file. After this time the file will be refreshed with new data. If 0 the global cache time from Elxis configuration will be used. To make your script faster set properly this option regarding what your application does. If, for example, you get a remote XML file that is being refreshed once per day set the cachetime to 86400 (1 day).
  • (boolean) mlang If true Elxis Cache will save a separate instance of your data for each language. Enabled it only on multi-lingual data.
  • (boolean) force If true, cache will be used even if cache is disabled in Elxis configuration. If false, cache will be used only if it is enabled in Elxis configuration.
  • (string) extension The extension (file type) of the saved cached file. If you plan to save raw PHP code (eg. an array containg some data) use php. For the remote XML workcase we will use xml. Allowed extension types: php, xml, txt, html, css, js, csv.

Method begin may return the following result (integer):

  • -1 Error, can't generate required folder (parameter group below) inside repository/cache/ folder
  • 0 Error, cache is disabled in Elxis configuration
  • 1 The file exists in cache and hasn't expired.
  • 2 The file does not exist in cache or exists but has expired and needs to be refreshed.

Usage example
Cache an XML feed from CNN web site in our test application and save it in cache for 28800 seconds (8 hours) even if cache is disabled in Elxis configuration ($force = true). Disable multilingual caching ($mlang = false) as this feed is always in English.

$eCache = eFactory::getCache();
$state = $eCache->begin('test', 'cnnfeed', '', 28800, false, true, 'xml');

If state value is 1 everything is OK and we can get the cached item from cache. If state is 2 then item has expired and we need to refresh it. On any other value of state cache can not be used and we should continue without it. For our example the cached item will be saved like that:

repository/cache/test_cnnfeed.xml

After the begin method if state is 1, you can get the data in 2 ways, using fetch or fetchContents methods.


fetch

Includes the cached file.
Tip: Use it only if the cached data dont need any manupulation before echoing to the browser or if your cached file is php.

public function fetch()

fetchContents

Get the cached file contents as a string.

public function fetchContents()

store

Save data into cache.
Tip: use it when state value is 2

public function store($data)
  • (string) data the data to save into cache file.

clear

Delete all files inside a cache folder (group) and the folder it self.

public function clear($group='')
  • (string) group the cache folder. Attention: If empty all cache items will be deleted!

clearItems

Delete selective items within a group (folder).

public function clearItems($group, $filter)
  • (string) group the cache folder, it can be an empty string for the cache root folder.
  • (string) filter Only files matching (starting from) this filter will be returned.

getError

Get the last generated error message.

public function getError()


Real world example

Real world example of using the elxisCache library.

//In $xml we will put the XML data from cache or the remote host.
$xml = '';
//Begin Elxis Cache
$eCache = eFactory::getCache();
$state = $eCache->begin('test', 'cnnfeed', '', 28800, false, true, 'xml');
//if state is 1 get the cached item contents and put them in $xml variable.
if ($state == 1) {
$xml = $eCache->fetchContents();
}

//If $xml is still empty we need to fetch the data from the remote host. We will use PHP's standard CURL library.
//As this part is outside the scope of this tutorial the code is simplified.
if ($xml == '') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/something/feed.xml');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$xml = curl_exec($ch);
curl_close($ch);
if (!$xml) {
//CURL failed, display some error message, exit, return, do what you think best depending on your application
exit('Could not load data from remote host!');
}
}

//$xml now contains "something" from cache or the remote host. We need to parse (read) it now.
//If the parse process fails, for example because the $xml variable doesn't contain valid data of an XML file, then display an error message.
//The XML parser is not part of this tutorial.
$row = someXMLParser($xml);
if (!$row) {
//Parser failed, display some error message, exit, return, do what you think best depending on your application
exit('Could not parse XML file!');
}

//Parsing was successful, so we have a good XML file.
//If cache state is 2 we need to save the data in $xml variable in cache (create/refresh cached file).
if ($state == 2) {
$eCache->store($xml);
}

//Do something with the parsed data in $row variable.
displaySomeNews($row);

That's it. Thanks for reading.
Ioannis Sannos

It has been read 6878 times
Elxis APC
Previous article
Elxis APC
elxisDocument
Next article
elxisDocument

You are free to copy, distribute and transmit the articles in this site for non-commercial purposes.
Creative Commons 3.0