The menu is created dynamically from the data inserted in the database earlier. But each time the website displays the menu it need to query the database, fetch the result and create the markup over and over again. This leads to a slower page load. Here comes the utility of caching. Generally the main menu is not changed frequently. So the HTML created by PHP may be saved in server and served to the client without any dynamic rebuilding. This will speed up page load time. After a predefined frequency the cache will be rebuilt automatically. Thus the change made to the database will be reflected in the main menu. The attached version of the menu is caching enabled. Test the difference between the previous version (http://layzend.info/2011/06/20/multi-level-category-management-part-3/) where caching is not enabled.
To enable cache you have to just write a few line of codes. First of all include the “lzcache.class.php” file. create an instance of “lzcache” in global scope. Pass the cache directory path and cache refresh frequency in seconds. Search for the menu in cache by the cache key ‘category_list’. If it is not yet present the menu will be built from the database and the HTML will be stored in cache. Afterwards, when the page is reloaded the cache key ‘category_list’ will be present in the cache and it will be served from the cache without rebuilding the menu again, which will speed up the menu loading time drastically.
// 1 hour of cache refresh frequency
// cache directory path => ./cache
// cache refrsh time => (3600/60) = 1hour
$cache = new lzcache('./cache',3600);
// menu
$menu = new lzmlm();
// using the class to cache the menu
if(!$cache->have('category_list'))
{
$menu = $menu->apycomMenu();
$cache->set($menu,'category_list');
} else {
$menu = $cache->get('category_list');
}
echo $menu;