Caching

Caching For developers

By caching reused data, you can prevent many database queries, resulting in improved performance. MODX Revolution offers a number of different caching features at different levels in your application. Caching in MODX is primarily handled by the base modCacheManager class, which extends xPDOCacheManager and allows for section-specific cache handlers. The default implementation writes caches to files in the core/cache/ folder.

If you define a custom MODX_CONFIG_KEY, the cache manager will write to core/cache/MODX_CONFIG_KEY/

General Caching Terminology and Behavior

MODX uses different sections for different types of cached data. In simple terms, a section is a folder in the core/cache/ directory, but the real value of sections is that each section can be assigned different cache handlers. Cache handlers derive from the xPDOCache class and provide a single API for storing, reading, and removing cache entries.

The default cache handler xPDOFileCache writes the cache to the file system in the core/cache/ folder, but there are other cache handlers available in the core for APC (xPDOAPCCache), memcache(d) (xPDOMemCache, xPDOMemCached), and WinCache (xPDOWinCache).

MODX Core Cache Sections

There are several sections in the core. You can easily identify them by looking in the core/cache/ folder for the default cache configuration.

You don’t usually need to work with cached data directly (use the available APIs instead), but to understand the core of MODX, here we’ll go through the main sections and briefly describe their purpose and content.

As we’ll discuss later, custom providers can also be used in development.

  • action_map contains a large array of all actions (IDs referencing controllers and namespaces) that can be accessed in the manager. Since actions are deprecated and no longer used in 2.3, never rely on them.
  • auto_publish contains a Unix timestamp that determines when a resource should be automatically published or unpublished (see ModCacheManager.autoPublish())
  • context_settings for each context in the site contains a resource map (parent and child document IDs), an alias map, plugins used in the context, and access policies.
  • db the database cache section is used when the cache_db system or context setting is enabled, and contains raw result sets for xPDO getObject/getCollection queries. More on this below.
  • includes – This isn’t really a cache partition, but it contains PHP files where snippets and plugins are wrapped in function calls for easy execution by the core. See the scripts for the snippets and plugins cache partition.
  • logs – This isn’t really a cache partition either, but it contains the error.log file and sometimes other log files (like the installation log).
  • menu – Contains a multidimensional array of the manager’s top menu for each manager language.
  • mgr is not a true cache partition, but is used by Smarty and Google Minify in 2.2 to write cache files.
  • registry – This is the default directory for modRegistry, where log files are written. Not a true cache section.
  • resource contains a partial resource caching mechanism organized by context and resource ID. These cache files contain metadata for the resource, a cached representation of the resource (_content) with uncached tags, resource access policies, and elements and their sources used to process the resource.
  • rss is not a true cache section, but is used by MagpieRSS (RSS panel widgets) to write to the cache.
  • scripts contains the source of snippets and plugins that are subsequently written to the includes cache folder.
  • setup is not a true cache section, but is used by the MODX installer to cache Smarty templates.
  • system_settings contains the global MODX configuration and system settings. This section is loaded first when requested in MODX. Since alternate cache handlers for sections are stored in the system settings, this section cannot be loaded from another cache handler in this way.

To change the cache handler for a specific cache partition, simply create a new system (or context) setting named cache_PARTITION_handler (such as cache_resource_handler or cache_scripts_handler) and set it to the cache handler you would like to use. By default, xPDOFileCache is used, but other handlers are available for APC, memcache(d), and wincache.

Database Caching

If you enable the cache_db system setting, MODX can automatically cache database result sets retrieved by any xPDOCriteria or xPDOQuery instance. This includes all result sets representing xPDOObjects or collections of xPDOObjects returned by methods such as getObject and getCollection.

This feature can be enabled in environments where database access is more expensive than the PHP file connection time, such as when using an external database server, or configured for environments with memcached, APC, or other caching systems available. This is a separate cache section in MODX, so it can be configured with other cache handlers. See xPDO Caching for more information.

Refreshing the MODX Core Cache

To refresh any of the core MODX cache partitions, use the modCacheManager->refresh() method. The minimal call has no parameters and will refresh all core cache partitions.

$modx->cacheManager->refresh();

Alternatively, you can define a $providers array with a partition of key => $partitionOptions elements.

// Refresh only web and web2 context settings
$modx->cacheManager->refresh(array('context_settings'=>array('contexts'=> array ('web', 'web2')));

The second parameter $results is passed by reference and will contain the results of each cache partition. Depending on the partition, this can be a boolean value or an array with additional information about the result of updating a particular partition. The function itself returns a boolean value indicating whether any of the partitions returned a boolean value false.

Programmatic (Custom) Caching

By interacting with modCacheManager, you can easily cache any type of data. There are several useful functions you can use to maintain a working cache. By using modCacheManager with a custom section (though not required), users of your code can change the cache handler and store data in a memcached, APC, or WinCache instance instead of the default file cache.

ModCacheManager (derived from xPDOCacheManager) provides the following useful methods:

  • add($key, $var, $life = 0, $options = array()) is used to add a value to the cache, but only if it does not already exist or has expired.
  • replace($key, $var, $life = 0, $options = array()) is used to replace an existing cached value with another.
  • set($key, $var, $life = 0, $options = array()) is used to set a value to the cache, regardless of whether it already exists (overwritten) or not (added).
  • delete($key, $options = array()) removes a cached value from the cache.
  • get($key, $options = array()) gets the cached value from the cache.
  • clean($options = array()) clears (removes) the entire cache provider. Make sure you define xPDO::OPT_CACHE_KEY in the options array.

In general, you can use get($key) and set($key, $value) to get and set values, respectively, but additional methods provide additional control over how the data is managed.

The $options array can contain the following options, which specify the cache partition to write to, the cache handler to use, and the default expiration time.

  • xPDO::OPT_CACHE_KEY – the write cache partition.
  • xPDO::OPT_CACHE_HANDLER – the cache handler to use. Typically, you don’t want to hardcode this, but it makes sense to let a specific implementation handle the cache handler using the system settings (i.e. the cache_PARTITION_handler system settings).
  • xPDO::OPT_CACHE_EXPIRES – the default expiration time.

Example 1: Simple cache add and get

$str = 'My test data for cache.';

// Write data to the default cache partition with an expiration of 2 hours.
$modx->cacheManager->set('testdata', $str, 7200);

// Get data from cache again. Returns zero if cache is unavailable or expired.
$str = $modx->cacheManager->get('testdata');

Example 2. Adding and getting cache from a custom partition

$str = 'My test data for cache.';

$options = array(xPDO::OPT_CACHE_KEY=>'mypartition',);

// Write data to the default cache partition with an expiration of 2 hours.
$modx->cacheManager->set('testdata', $str, 7200, $options);

// Get data from the cache again. Returns zero if the cache is unavailable or expired.
$str = $modx->cacheManager->get('testdata', $options);

Rate article
MODX 3
Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.