Documentation Menu

1.5 Template Project

The Joomla! Documentation Working Group is running a project to develop detailed reference and tutorial material on Joomla! 1.5 templates.  There is a project page on the documentation wiki where you can see the work in progress and help us by contributing your knowledge.

Who's Online

We have 3 guests online

Help Site License

The Joomla! Help Site content is copyright © 2005 - 2008 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution NonCommercial ShareAlike 2.5. Some parts of this website may be subject to other licenses.
Home arrow patTemplate arrow Customisation arrow Caching

Caching PDF Print E-mail

How does it work?

When you are calling patTemplate::readTemplatesFromInput(), patTemplate will include and instantiate the desired reader which will then load and analyze the template you specified. This will be done everytime the template is requested although the process is not influenced by any variables or user feedback.

This technique has two drawbacks:

1. The reader class consist of 1400+ lines of code, which have to be compiled
2. The reader makes use of preg_* functions, which can get time consuming

To get rid of these performance brakes, I implemented the template cache, which implements a quite simple functionality: After the reader analyzed the template and returns an array containing the structure, the template cache will serialize this structure and store it with a unique key. On the next request, patTemplate asks the template cache, whether there's a stored structure for a specific key. If yes, it will be usnerialized and used instead of reading the template again.
Using a template cache

Like all patTemplate modules, using a template cache is easy. Basically, you just need to add one line of code to your scripts.

01        <?PHP
02        require_once 'pat/patErrorManager.php';
03        require_once 'pat/patTemplate.php';
04       
05        $tmpl = &new patTemplate();
06        $tmpl->setRoot( 'templates' );
07       
08        /**
09        * Use a template cache based on file system
10        */
11        $tmpl->useTemplateCache( 'File', array(
12                                                'cacheFolder' =>'./tmplCache',
13                                                'lifetime' =>60 )
14                                              );
15       
16        $tmpl->readTemplatesFromInput( 'page.tmpl', 'File' );
17       
18        $tmpl->displayParsedTemplate();
19        ?>


The first parameter in the call to useTemplateCache() defines which cache should be used. if you are unsured, which caches you have installed, take a look at the folder patTemplate/TemplateCache. The second parameter is an array with all parameters for the template cache. You'll have to check the documentation of the template cache you are using for a list of all supported parameters.

In the example that uses the 'File' cache, there are two parameters:

cacheFolder defines, where the cache files will be stored

lifetime defines, how long the cache is valid. In this case, we use a cache for 60 seconds. You may also set the cache to 'auto', if you want the cache to be rebuilt, when the source file changes.
Creating a new template cache

patTemplate ships with a template cache, that stores data on the filesystem. If you need a faster storage container, like shared memory, you may easily implement it.

Create a new file in patTemplate/TemplateCache and create a class, that extends patTemplate_Cache. In this class, you only need to implement the following methods:

array patTemplate_TemplateCache::load( string key, int modificationTime )

boolean patTemplate_TemplateCache::write( string key, array templates )

The load() method will receive a unique key as well as the time, when the original file has been modified, if the reader supports this feature. You will have to check, whether there is a cache file for the specified key and whether it still is valid. If the file is valid, you will have to unserialize the stored data and return the resulting template structure to patTemplate.

The write() method will receive the unique key, as well as the template structure, that has to be stored. Just serialize it and store it with the key, so it can be loaded at a later point.

Take a look at the code

To fully grasp, how the template cache works, take a look at the 'File' cache:

01        <?PHP
02        /**
03        * patTemplate Template cache that stores data on filesystem
04        *
05        * Possible parameters for the cache are:
06        * - cacheFolder : set the folder from which to load the cache
07        * - lifetime : seconds for which the cache is valid, if set to auto, it will check
08        *   whether the cache is older than the original file (if the reader supports this)
09        *
10        * @package       patTemplate
11        * @subpackage    Caches
12        * @author        Stephan Schmidt <schst@php.net>
13        */
14        class patTemplate_TemplateCache_File extends patTemplate_TemplateCache
15        {
16           /**
17            * parameters of the cache
18            *
19            * @access    private
20            * @var        array
21            */
22            var $_params = array(
23                                 'cacheFolder' =>'./cache',
24                                 'lifetime'       =>'auto'
25                                );
26       
27           /**
28            * load template from cache
29            *
30            * @access   public
31            * @param    string           cache key
32            * @param    integer          modification time of original template
33            * @return   array|boolean    either an array containing the templates or false cache could not be loaded
34            */
35            function load( $key, $modTime = -1 )
36            {
37                $filename = $this->_getCachefileName( $key );
38                if( !file_exists( $filename ) || !is_readable( $filename ) )
39                    return false;
40       
41                $generatedOn = filemtime( $filename );
42                $ttl         = $this->getParam( 'lifetime' );
43                if( $ttl == 'auto' )
44                {
45                    if( $modTime <1 )
46                        return false;
47                    if( $modTime >$generatedOn )
48                        return false;
49                    return unserialize( file_get_contents( $filename ) );
50                }
51                elseif( is_int( $ttl ) )
52                {
53                    if( $generatedOn + $ttl <time() )
54                        return false;
55                    return unserialize( file_get_contents( $filename ) );
56                }
57               
58                return false;
59            }
60           
61           /**
62            * write template to cache
63            *
64            * @access    public
65            * @param     string        cache key
66            * @param     array        templates to store
67            * @return    boolean        true on success
68            */
69            function write( $key, $templates )
70            {
71                $fp = @fopen( $this->_getCachefileName( $key ), 'w' );
72                if( !$fp )
73                    return false;
74                flock( $fp, LOCK_EX );
75                fputs( $fp, serialize( $templates ) );
76                flock( $fp, LOCK_UN );
77                return true;
78            }
79           
80           /**
81            * get the cache filename
82            *
83            * @access   private
84            * @param    string        cache key
85            * @return   string        cache file name
86            */
87            function _getCachefileName( $key )
88            {
89                return $this->getParam( 'cacheFolder' ) . '/' . $key . '.cache';
90            }
91        }
92        ?>


As you can see, implementing a template cache is really simple and should not pose a problem to the experienced PHP developer.

Last Updated ( Friday, 31 December 2004 )
 
< Prev   Next >