Applications of Fragment Caching

Useful method to cache partials or widgets in your application.

Useful when the information is retrieved every hour or more frequently than average pages.

Cache discrete portions of code which do not need to be refreshed for every new page load.

Minimum setup required and server platform agnostic

Speeds up dynamic views

Modular functionality

Strategies of Fragment Caching

This entails the strategies of how efficiently we can cache web-page fragments. Whether we have to cache a table which represents the yearly sales results of a company or one which displays the list of courses in the registration system of a university application, caching eliminates the need to generate a table for each such web request. It is effectively a layer on the top of data caching.

The following construct is used for Fragment Caching

if ($this->beginCache($id)) {

    // ... generate content here ...

    $this->endCache();
}


Fragment Caching in Wordpress

Wordpress is an online, open source website creation tool written in PHP. This is also one of the current best blogging and CMS(Content Management System). Naturally, we have hordes of content creators, bloggers, creative professionals and students accessing these sites on a regular basis. The need for fragment caching arises to provide a seamless user-friendly experience such that accessing widgets, articles is much faster.

Particular fragments of the web page where a lot of server side scripting is done is loaded into the cache for later retrieval. The next time we load the page , it will be loaded from the cache, bypassing the lengthy database queries and quickly rendered in the browser. Fragment caching allows us to select which parts of the web page need to cache and which parts will be untouched by caching. This leaves a lot of freedom in the hands of the web developer to cache portions of code which are beneficial.

Example of fragment caching in Wordpress

This created a new Fragment variable called FragmentCache which will first provide the output and then store it into cache for the next page visit

<?php
$cache = new FragmentCache();
if ( ! $cache->output() ):
?>
  <div>
    <h1>My Cached Content</h1>
    <?php output_expensive_queries(); ?>
  </div>

<?php
  $cache->store();
endif;
?>

WordPress Object Cache

WP_Object_Cache is WordPress' class for caching data which may be computationally expensive to regenerate, due to the processing of intricate SQL queries. The object cache is defined in wp-includes/cache.php. By default, the object cache is non-persistent. This means that data stored in the cache resides in memory only and only for the duration of the request. Cached data will not be stored persistently across page loads unless you install a persistent caching plugin.


References