Caching: The Fast Becomes Faster

From Nephtali Documentation

Jump to: navigation, search

Nephtali is fast out-of-the box because it is relatively small and simple. However, there are certainly situations where you need every little micro-second, or you're webpage makes use of web services for data on the page, leading to slow-loading pages. In these situations, Nephtali facilitates caching.

There are many strong caching options out there (APC, memcache, etc.), and just as with javascript frameworks, Nephtali tries to allow you to use the tool you prefer.

Example 1: Caching The Final Result

In this first example, you see the code responsible for caching the Nephtali homepage (useful because the homepage makes use of 2 separate web services for data on the page):

n\cache\register(
    $stage = n\constant\CACHE_FINAL,
    $fetch_func = function($markup)
    {
        $homepage_markup = apc_fetch("homepage");
	
        if ($homepage_markup !== false)
        {
            return $homepage_markup;
        }
        else
        {
            return null;
        }
    },
    $save_func = function($markup)
    {
        apc_store("homepage", $markup, 3600);
    }
);

The example code shows the basic registration of a caching mechanism. You just tell Nephtali which stage of the page you're caching and the functions that handle getting and setting the cache. You could just as easily utilize memcache for this example, or some other caching option.

Example 2: Caching After Templates Have Been Applied

In this second example, we look at how you can cache the page after all the templates have been applied (but before any of the pipes have been rendered.) Perhaps the data displayed in the pipes of the page changes too frequently to allow caching the entire page at the end of the process. However, caching the page markup after templates have been applied allows you to still improve performance whilst accommodating the frequently updated data in the pipes.

n\template\register($path = 'ntemplates/test_template.php', $regions = array('header', 'footer', 'content'));
n\template\register($path = 'ntemplates/two_column_template.php', $regions = array('col1','col2'));

n\cache\register(
    $stage = n\constant\CACHE_AFTER_TEMPLATES,
    $fetch_func = function($markup)
    {
        $template_markup = apc_fetch("templates");
		
        if ($template_markup !== false)
        {
            return $template_markup;
        }
        else
        {
            return null;
        }
    },
    $save_func = function($markup)
    {
        apc_store("templates", $markup, 60);
    }
);

This should look pretty similar to the first example. The differences include the new value for the stage (after templates), and the minor differences between the handling of the getting and setting of the cache.