JFactory/getCache
From Joomla! Documentation
< JFactory
Returns a reference to the global cache object, only creating it if it doesn't already exist. The object returned will be of type JCache.
Syntax
object JCache getCache( $group, $handler, $storage )
where:
| Argument | Data type | Description | Default |
|---|---|---|---|
| $group | string | The cache group name. This allows separate caches to be created by assigning them a unique group name. | |
| $handler | string | The cache handler to use. For information on cache handlers see JCache. | 'callback' |
| $storage | string | The cache storage method to use. For information on cache storage methods see JCache. | null |
Example
In this example, a simple callback cache is implemented. This caches the results of 'expensiveMethod' so that for a given set of arguments the result is only computed once. For more information about caching see JCache.
// Define a class to contain the computationally-expensive method. class expensiveClass { function expensiveMethod ( $signature ) { static $instances; if (!isset( $instances )) $instances = array(); if (empty( $instances[$signature] )) { // Something that is resource-intensive to produce, here simulated // by calculating the MD5 hash of the signature. $instances[$signature] = md5( $signature ); echo 'Cache miss'; } else { echo 'Cache hit '; } return $instances[$signature]; } } // Create a cache instance. $cache =& JFactory::getCache( 'myCache' ); // Specify the class and method that will produce the data to be cached. $method = array( 'expensiveClass', 'expensiveMethod' ); // Now execute some code that will use the cache. echo ' : ' . $cache->get( $method, 'abc' ) . "\n"; echo ' : ' . $cache->get( $method, 'efg' ) . "\n"; echo ' : ' . $cache->get( $method, 'abc' ) . "\n"; echo ' : ' . $cache->get( $method, 'hij' ) . "\n"; echo ' : ' . $cache->get( $method, 'klm' ) . "\n"; echo ' : ' . $cache->get( $method, 'hij' ) . "\n";
This produces output like this:
Cache miss : 900150983cd24fb0d6963f7d28e17f72 Cache miss : 7d09898e18511cf7c0c1815d07728d23 Cache hit : 900150983cd24fb0d6963f7d28e17f72 Cache miss : 857c4402ad934005eae4638a93812bf7 Cache miss : 3491f0dc1059a35bb1681b3bd67cb0d5 Cache hit : 857c4402ad934005eae4638a93812bf7
