How to implement view based caching

1. Introduction

Within a discussion in the forum, the idea of view based caching was born. Triggered by Alberto, we began to talk about performance optimization and various caching methods. The conclusion was, that caching of pieces of HTML is an effective way to gain performance.

This can be done by the cURL solution mentioned by Alberto or by view based caching. The benefit of view based caching method is, that the application itself must not be touched or adapted to the caching strategy. Within this article, I will talk about the idea of this technique and the implementation with the resources of the Adventure PHP Framework.

2. What about views?

First of all, let me say a few words about the notion view. Spoken in APF terminology, a view is nothing else, than a template file included within another - maybe a layout template of your web page. As described in the Page controller section, the presentation layer implementation of the APF features a generic page controller component, that analyzes APF style template files and generates a DOM tree out of the known tags.

Each tag consists of it's tag definition - something like

APF template
<my:tag attr1="value1" attr2="value2" />

and a class including the functionality of the tag. Each taglib must implemente the following methods, that are executed in the order presented in the code box:

PHP code
class MyTag extends Document { public function onParseTime() { } public function onAfterAppend() { } public function transform() { } }

To get a detailed idea, which functionality should be placed in which method, please have a look at the Implementation of tags tutorial.

So how can this fact be used to implement view based caching? Thanks to the generic DOM definition, the developer is able to implement own taglibs to enhance the core functionality or to satisfy the customer's requirements. This means, that the existing template including mechanisms can be used as a basis for view based caching.

3. Implementation

3.1. Let's get started

As described on the Standard taglibs page, the <core:importdesign /> tag imports a template specified by it's namespace and file name into the current DOM node. As I have mentioned above, this tag can be used to specify dedicated views within a layout template containg the header, footer or navigation functionality. Due to the fact, that we want to cache the content of special views, we can use this taglib as a basis.

To be sure about that, let us have a look at the taglib implementation:

PHP code
class ImportTemplateTag extends Document { public function onParseTime(){ $namespace = trim($this->getAttribute('namespace'); $template = trim($this->getAttribute('template'); $context = $this->getAttribute('context'); if($context !== null){ $this->context = trim($context); } $language = $this->getAttribute('language'); if ($language !== null) { $this->setLanguage($language); } $incParam = $this->getAttribute('incparam'); if ($incParam === null) { $incParam = 'pagepart'; } ... $this->loadContentFromFile($namespace, $template); $this->extractDocumentController(); $this->extractTagLibTags(); } }

The main functionality is to evaluate the tag's attributes injected on parse time, to load and parse the content using the extractDocumentController() and extractTagLibTags() methods. The only thing, that is missing, is the caching part!

3.2. The cache manager

For caching purposes, the framework contains a flexible caching component with various backends. In this case, we simply use the text cache mechanism described in the text cache provider section in the documentation. In order to use it we have to provide a configuration section within the cache configuration file as described in the docs. The section might look like this:

APF configuration
[view_based_cache] Provider = "APF\tools\cache\provider\TextCacheProvider" Active = "true" BaseFolder = "/path/to/my/cache/base/folder" Namespace = "view\one"

To read and write the cache respectively, we can use the following code fragment:

PHP code
// get the cache manager $cMF = $this->getServiceObject('APF\tools\cache\CacheManagerFabric'); $cM = $cMF->getCacheManager('view_based_cache'); // calculate cache key $cacheKey = /* ... */; // read the cache $cacheContent = $cM->getFromCache($cacheKey); // write to the cache if($cacheContent === null){ $cacheContent = /* generate content */; $cM->writeToCache($cacheKey,$cacheContent); }

3.3. The final assembly

To get things working let's put the pieces together:

PHP code
namespace EXAMPLE\vbc\pres\taglib; use APF\core\pagecontroller\ImportTemplateTag; use APF\tools\cache\CacheManagerFabric; use APF\tools\cache\key\SimpleCacheKey; class CachedImportTemplateTag extends ImportTemplateTag { private $cacheContent = null; public function onParseTime() { // gather tag configuration $cacheConfig = $this->getAttribute('cacheconfig'); $cacheKey = new SimpleCacheKey($this->getAttribute('cachekey')); // get the cache manager /* @var $cMF CacheManagerFabric */ $cMF = $this->getServiceObject('APF\tools\cache\CacheManagerFabric'); $cM = $cMF->getCacheManager($cacheConfig); // clear the cache if desired if (isset($_REQUEST['clearcache']) && $_REQUEST['clearcache'] == 'true') { $cM->clearCache($cacheKey); } // try to read from the cache $this->cacheContent = $cM->getFromCache($cacheKey); // check if the document was cached before. If not // execute the parent's onParseTime() if ($this->cacheContent === null) { parent::onParseTime(); } } public function transform() { // generate the node's output or return the cached content if ($this->cacheContent === null) { // gather tag configuration $cacheConfig = $this->getAttribute('cacheconfig'); $cacheKey = new SimpleCacheKey($this->getAttribute('cachekey')); // get the cache manager /* @var $cMF CacheManagerFabric */ $cMF = $this->getServiceObject('APF\tools\cache\CacheManagerFabric'); $cM = $cMF->getCacheManager($cacheConfig); // generate output and cache it $output = parent::transform(); $cM->writeToCache($cacheKey, $output); // return the tag's output return $output; } return $this->cacheContent; } }

As you can see, the onParseTime() and transform() methods are enhanced with the cache handling. To store the cache content and to be able to decide, if cached content is available, the private member variable cacheContent was introduced. Please note, that the code duplication within the two methods is just there to illustrate the function flow.

4. Usage

The usage of the tag is not different to the usage of the <core:importdesign /> tag. The only difference is, that we have to provide a configuration section for the cache manager:

APF template
<core:addtaglib class="EXAMPLE\vbc\pres\taglib\CachedImportTemplateTag" prefix="cache" name="importdesign" /> <cache:importdesign namespace="VENDOR\..\namespace" template="my_template" />

5. Conclusion and outlook

Thanks to the generic page controller implementation of the APF it is quite easy to implement a view based cache concept using tags. To have a robust and reusable taglib, the class printed above should have one or two more attributes, specifying the cache configuration section and perhaps the cache key. Doing so, the taglib is surely reusable within other projects or within several parts of your application.

Concerning the cache control, you have the choice to either clear the cache manually or use a cache provider, that can handle cache file life time. If you have the need, to add automatical refreshment, have a look at the enhancement chapter on the CacheManager page.

6. Download

To try this out, I have created a sample implementation for PHP 5 including the enhancements written about in chapter 5. If you want to run the sample code, just download and extract package apf-vbc-example-* from the Downloads page into the DOCUMENT_ROOT of your web server. Please be sure, that the user running your HTTP server has write permissions to the current folder. If you like to use another folder to store the cache, adapt the file /APF/config/tools/cache/sites/vbc/DEFAULT_cacheconfig.ini.


Do you want to add a comment to the article above, or do you want to post additional hints? So please click here. Comments already posted can be found below.
There are no comments belonging to this article.

In order to provide a state-of-the-art web experience and to continuously improve our services we are using cookies. By using this web page you agree to the use of cookies. For more information, please refer to our Privacy policy.