Found at: http://publish.ez.no/article/articleprint/16/

Page caching with templates



If you have implemented a PHP application using an object oriented approach and are disappointed with the performance you get, then this article is worth looking at. Here I will explain how you can use templates to cache your web pages and serve pure static pages. Using this technique you can have complex algorithms for rendering articles, or whatever you like, and still get the performance of static pages.

If you are wondering about how templates works please read the article about block templates here. This first code snippet shows how you can implement the page caching mechanism. Here I check if page caching is enabled, if it is disabled the page is just generated as usual. If page caching is enabled the code checks for a cached version. If there exists no cached versions of the page, one is generated.


// read from .ini file 
$PageCaching = "enabled"

// check if caching is enabled
if ( $PageCaching == "enabled" )
{
    $cachedFile = "cache/page.cache";
                    
    if ( file_exists( $cachedFile ) )
    {
        include( $cachedFile );
    }
    else
    {
        createPage( true, $cachedFile );
    }            
}
else
{
    createPage( false );
}



The createPage() function is listed below. I have made it as simple as possible to demonstrate the topic in focus, page caching. As you see from the code we use templates as usual, and if $generateStaticPage is false the template is parsed as it normally does. The special bit about this code is when $generateStaticPage is set to true. A file is then opened for write and the template is parsed out to a variable, $output. This $output is then printed to the client and stored in a file.


function createPage( $generateStaticPage, $cachedFile = "" )
{
    include_once( "template.inc" );

    $t = new eZTemplate( "templates/" );

    $t->set_file( "page_tpl" => "page.tpl" );

    // perform calculations
         
    $t->set_var( "template_variable", $value );

    if ( $generateStaticPage == true )
    {
        $fp = fopen( $cachedFile, "w+" );

        $output = $t->parse( $target, "page_tpl" );

        // display the page contents and write it to file
        print( $output );
        fwrite ( $fp, $output );
        fclose( $fp );
    }
    else
    {
        $t->pparse( "output", "page_tpl" );
    }
    
}


The next time this page is visited the pure static version of the page is served and you don't get so much load on your server.

Simple isn't it?


| Back to normal page view |