Path

ez components / documentation / api reference / 2006.2 / cache


eZ Components 2006.2

Cache

[ Tutorial ] [ Class tree ] [ Element index ] [ ChangeLog ] [ Credits ]

Introduction

The Cache package provides a collection of lightweight classes to cache different kinds of data. Beside that, it provides a manager class, which takes care of instantiating and reusing caches.

Class overview

This section gives you an overview on all classes, that are intended to be used directly.

ezcCacheManager
This is the manager, which will take care of your caches. It is optional to use the manager, but recommended if your application needs to cache different data for different purposes. It allows you to configure all needed caches in a central place and to retrieve them through the ezcCacheManager. The cache manager will store only the configurations at first and only instantiate the cache object itself when you request it for use.
ezcCacheStorage
This is the base class for all cache storages (the cache classes themselves). All cache classes inherit from this base class.
ezcCacheStorageFilePlain
Cache objects of this class are capable to store plain text data on the file system. It utilizes the file_get_contents() and file_put_contents() functions of PHP.
ezcCacheStorageFileArray
In contrast to ezcCacheStorageFilePlain, objects of this class can store array structures and will keep PHP data types intact. The ezcCacheStorageFileArray class generates PHP code, which will be stored on the file system. Restoring data from the cache uses the require() construct.
ezcCacheStorageFileEvalArray
Objects of this storage class follow a similar approach like ezcCacheStorageFileArray and is also capable of storing array structures. The major difference between both classes is, that ezcCacheStorageFileEvalArray will use PHPs eval() method to restore the cached data, instead of using required() to restore the cache data. This has the effect, that the stored data will not be cached again in PHP accelerators like APC. This might be desirable, if you store large amounts of data at once.

Usage

Terminology

Cache
A location that stores cache item. A cache is created with the ezcCacheManager::createCache(), preferrably at the beginning of your script. A cache with it's cache identifier - the first parameter to ezcCacheManager::createCache() - can only be created once. After it has been created at the beginning of your request you can obtain a reference to it throughout the whole request by calling ezcCacheManager::getCache() with as first parameter the $id with which it was created.
Cache identifier
An identifier that uniquely identifies a cache which contains a number of cache item s.
Cache item
One single entry stored in the cache. Cache items can be stored and retrieved by using the ezcCacheStorage object that is returned by calling ezcCacheManager::getCache(). Cache items use a cache key to identify specific entries in the cache.
Cache key
A string representing a single cache item in a cache.
Attribute
Additional information to complement the cache key for doing operations on cache item s.

A simple example

This example shows how to create and use a simple cache with the ezcCacheManager:

  1. <?php
  2. 
  3. require_once 'tutorial_autoload.php';
  4. 
  5. $options = array(
  6.     'ttl'   => 30,
  7. );
  8. 
  9. ezcCacheManager::createCache'simple''/tmp/cache/plain''ezcCacheStorageFilePlain'$options );
 10. 
 11. $myId 'unique_id_1';
 12. $mySecondId 'id_2';
 13. 
 14. $cache ezcCacheManager::getCache'simple' );
 15. 
 16. if ( ( $dataOfFirstItem $cache->restore$myId ) ) === false )
 17. {
 18.     $dataOfFirstItem "Plain cache stored on " date'Y-m-d, H:i:s' );
 19.     $cache->store$myId$dataOfFirstItem );
 20. }
 21. 
 22. if ( ( $dataOfSecondItem $cache->restore$mySecondId ) ) === false )
 23. {
 24.     $dataOfSecondItem "Plain cache 2 stored on " date'Y-m-d, H:i:s' );
 25.     $cache->store$mySecondId$dataOfSecondItem );
 26. }
 27. 
 28. var_dump$dataOfFirstItem$dataOfSecondItem );
 29. 
 30. ?>

In the options for the cache to create, the time-to-life is defined. If left out, the cache has a lifetime of 24 hours. In this place, a lifetime of 30 seconds is defined. On line 9 the cache configuration is stored in the cache manager. The cache created uses the cache identifier "simple" and will reside in the directory /tmp/cache/plain (Note: This directory must exists and must be writable to the user running the code, else you will get an ezcBaseFileNotFoundException or an ezcBaseFilePermissionException!). To store a cache item, the storage class ezcConsoleStorageFilePlain will be used and as defined before, the stored data will expire after 30 seconds.

Line 11 defines a cache key for the data to cache. The next line defines a second unique cache key for a second cache item. After that (line 14), the cache object is retrieved from the ezcCacheManager (the object itself is created right now, since we access it for the first time). The lines 16 and 22 show how to check for cached data: The method ezcCacheStorage::restore() will return bool false, if no valid cache data is found for a given ID.

In case the cache storage did not find valid data, the data will be generated and stored in the cache afterwards (lines 17-18 and 24-25). The last line shows the data, so you can follow how it's cached for 30 seconds, by simple running the example multiple times in a short time frame. After 30 seconds the cache data will become invalid and will be regenerated.

Using multiple caches

The following example shows how the cache manager deals with multiple caches:

  1. <?php
  2. 
  3. require_once 'tutorial_autoload.php';
  4. 
  5. $optionsPlain = array(
  6.     'ttl'   => 30,
  7. );
  8. $optionsArray = array(
  9.     'ttl'   => 45,
 10. );
 11. 
 12. ezcCacheManager::createCache'plain''/tmp/cache/plain''ezcCacheStorageFilePlain'$optionsPlain );
 13. ezcCacheManager::createCache'array''/tmp/cache/array''ezcCacheStorageFileArray'$optionsArray );
 14. 
 15. $myId 'unique_id_2';
 16. 
 17. $cache ezcCacheManager::getCache'plain' );
 18. 
 19. if ( ( $plainData $cache->restore$myId ) ) === false )
 20. {
 21.     $plainData "Plain cache stored on " date'Y-m-d, H:m:s' );
 22.     $cache->store$myId$plainData );
 23. 
 24.     sleep);
 25. }
 26. 
 27. echo "Plain cache data:\n";
 28. var_dump$plainData );
 29. 
 30. $cache ezcCacheManager::getCache'array' );
 31. 
 32. if ( ( $arrayData $cache->restore$myId ) ) === false )
 33. {
 34.     $arrayData = array( 
 35.         $plainData,
 36.         "Array cache stored on " date'Y-m-d, H:m:s'),
 37.         true,
 38.         23
 39.     );
 40.     $cache->store$myId$arrayData );
 41. }
 42. 
 43. echo "Array cache data:\n";
 44. var_dump$arrayData );
 45. 
 46. ?>

In the lines 12 and 13 you see how 2 caches are created. Each cache must reside in its own location and must have a different cache identifier. We use 2 different options for the lifetime of the caches to show how they act independently later.

Since the first cache reuses the location already used in example 1, we use a different cache key now. Lines 15 to 25 are almost identical to the code from example 1, except that the program will sleep for 2 seconds, when it generated new data for the plain cache, to show different generation times in the 2 caches.

On line 30 the second cache object is retrieved, which is capable of storing arrays. Therefore, we store the data from the plain cache here and additionally generate some more data, all stored in an array. Running this example multiple times will give you different results now after some time, since the second cache has a longer lifetime and will therefore hold its data longer than the first one.

Complex caching

As the next example shows, ezcCacheStorage classes are capable of more advanced features. This example uses attributes to identify cached data, additionally to their cache key:

  1. <?php
  2. 
  3. require_once 'tutorial_autoload.php';
  4. 
  5. $options = array(
  6.     'ttl'   => 30,
  7. );
  8. 
  9. ezcCacheManager::createCache'array''/tmp/cache/array''ezcCacheStorageFileArray'$options );
 10. 
 11. $exampleData = array( 
 12.     'unique_id_3_a' => array( 'language' => 'en''section' => 'articles' ),
 13.     'unique_id_3_b' => array( 'language' => 'de''section' => 'articles' ),
 14.     'unique_id_3_c' => array( 'language' => 'no''section' => 'articles' ),
 15.     'unique_id_3_d' => array( 'language' => 'de''section' => 'tutorials' ),
 16. );
 17. 
 18. $cache ezcCacheManager::getCache'array' );
 19. 
 20. foreach ( $exampleData as $myId => $exampleDataArr )
 21. {
 22.     if ( ( $data $cache->restore$myId$exampleDataArr ) ) === false )
 23.     {
 24.         $cache->store$myId$exampleDataArr$exampleDataArr );
 25.     }
 26. }
 27. 
 28. echo "Data items with attribute <section> set to <articles>: " .
 29.      $cache->countDataItemsnull, array( 'section' => 'articles' ) ) .
 30.      "\n";
 31.      
 32. echo "Data items with attribute <language> set to <de>: " .
 33.      $cache->countDataItemsnull, array( 'language' => 'de' ) ) .
 34.      "\n\n";
 35. 
 36. $cache->deletenull, array( 'language' => 'de' ) );
 37. 
 38. echo "Data items with attribute <section> set to <articles>: " .
 39.      $cache->countDataItemsnull, array( 'section' => 'articles' ) ) .
 40.      "\n";
 41.      
 42. echo "Data items with attribute <language> set to <de>: " .
 43.      $cache->countDataItemsnull, array( 'language' => 'de' ) ) .
 44.      "\n\n";
 45. 
 46. ?>

After the creation of an array cache_, some sample data is created (lines 11-16). Each data is keyed by its cache key, which is associated with an array. This array will be used as the content and the attributes together later on. Attribute s describes a cache item in further detail. We will see, what to do with attribute s of a cache item later on, too.

In line 20 a foreach loop starts, which stores all example data in the cache. After that the method ezcCacheStorageFile::countDataItems() is used to let the storage object count its cache items. The first parameter here would be a cache key. When this is set, the method should always return 1 or 0, because only one cache item per cache key may exist. Instead, the cache items with the specified attribute are counted. The attributes to match are supplied as the second parameter. The first method call will return 3 (line 28), since we have 3 cache items which have the attribute "section" set to "articles". The second call (line 32) should return 2, because 2 data items have the attribute "language" set to the value "de".

On line 36 the storage object is told to delete all cache items, which have the attribute "language" set to "de". Therefore the next to calls to ezcCacheStorageFile::countDataItems() will return 2 and 0.

More Information

For more information, see the ezcCacheManager and ezcCacheStorageFile API documentation.

Last updated: Thu, 01 Nov 2007