Home >Documents >[Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

[Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

Date post:14-Apr-2018
Category:
View:215 times
Download:0 times
Share this document with a friend
Transcript:
  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    1/24

    Caching With PHP Cache_Lite

    By icarus

    This article copyright Melonfire 2000-2002. All rights reserved.

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    2/24

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    3/24

    Table of Contents

    .................. 1The Need For Speed

    ................... 2The Food Chain

    .................. 3Return Of The Jedi

    ................... 5Digging Deeper

    .................... 7In And Out

    ................... 9Different Strokes

    ................... 10Bits And Bytes

    ................. 12Of Form And Function

    ................. 14No News Is Good News

    .................... 16Cache Cow

    ..................... 20Endgame

    Printed from DevShed.com

    i

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    4/24

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    5/24

    The Need For Speed

    In the old days, a Web site usually consisted of static HTML pages and perhaps a few images to liven up

    the text. No more is this the case - sophisticated interfaces, streaming media, dynamically-generated

    content and other enhancements have all contributed to make todays Web more content-rich andinteractive than ever before. Most often, this is a Good Thing - greater accessibility and more quality

    content only make the Web more attractive to new users, and increase its usefulness to the community at

    large.

    However, there is a downside to this phenomenon as well. As sites become more content-rich, as their

    reliance on dynamic data sources increases, as their servers struggle to meet the thousands of requests

    coming in per minute, its only natural that the first casualty be the performance of the system. This is

    clearly visible in the Web, which today more closely resembles a slow traffic jam than a fast-moving

    freeway.

    Fortunately, there is a workaround, one that has been successfully used by many sites to provide a

    performance improvement: caching. And over the course of this article, Im going to show you a few

    examples of this technique in action, using my favourite language, PHP, and an open-source

    implementation of a server-side cache called Cache_Lite. Flip the page, and lets get started!

    Printed from DevShed.com

    1

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    6/24

    The Food Chain

    According to one definition (http://www.nottm.edu.org.uk/techi/networks/caching.pdf), a cache "is a store

    of information that is designed to improve the accessibility or availability of data to the user." Simply put,

    it is a location where copies of information are kept so they can sent to the user quickly and withoutwastage of already scarce Internet resources.

    Now, caches can be maintained at various levels depending on the requirements of the user. Unknown to

    many, the most commonly used caching mechanism is the Web browser itself. Modern Web browsers

    download content to a temporary location on the hard drive before rendering it to the user. And usually, if

    you visit the same page again, the browser will just pick it up from the local cache.

    At a workplace, its highly likely that you share your Internet connection with a large group of users. Here,

    the local cache of the Web browser does not always help to optimize the utilization of resources. In such a

    situation, network administrators often utilize the caching features of the proxy server used to share the

    Internet connection. This allows them to ensure that commonly-accessed sites are cached at the time of the

    first request. Subsequent requests to the same page are directly serviced from the proxy servers cache. Of

    course, this is not advisable for Web sites with highly dynamic content; proxy servers can be configured to

    avoid caching these pages.

    The above caching mechanism is often replicated at different levels. It is not uncommon to find ISPs

    caching content in order to reduce traffic that might otherwise eat up precious bandwidth on the Internet

    backbones.

    Finally, Web sites often implement complex caching mechanisms so as to serve their own content faster.

    This is the type of caching that this article discusses - caching your data at the application level. Keep

    reading.

    Printed from DevShed.com

    2

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    7/24

    Return Of The Jedi

    The Cache_Lite class comes courtesy of PEAR, the PHP Extension and Application Repository

    (http://pear.php.net). In case you didnt know, PEAR is an online repository of free PHP software,

    including classes and modules for everything from data archiving to XML parsing. When you install PHP,a whole bunch of PEAR modules get installed as well; the Cache_Lite class is one of them.

    In case your PHP distribution didnt include Cache_Lite, you can get yourself a copy from the official

    PEAR Web site, at http://pear.php.net- simply unzip the distribution archive into your PEAR directory and

    youre ready to roll!

    Lets begin with something simple - building a primitive cache using Cache_Lite object methods. Heres

    the code:

    Printed from DevShed.com

    3

    http://pear.php.net/http://pear.php.net/
  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    8/24

    Dont worry if it didnt make too much sense - all will be explained shortly. For the moment, just feast

    your eyes on the output:

    Do, or do not. There is no try. -- Yoda, Star Wars

    Now refresh the page - you should see something like this, indicating that the second occurrence of the

    page has been retrieved from the cache.

    Do, or do not. There is no try. -- Yoda, Star Wars [cached]

    Lets take a closer look at how this was accomplished, on the next page.

    Printed from DevShed.com

    4

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    9/24

    Digging Deeper

    When implementing a cache for your Web page, the first step is, obviously, to include the Cache_Lite

    class

    You can either provide an absolute path to this file, or do what most lazy programmers do - include the

    path to your PEAR installation in PHPs "include_path" variable, so that you can access any of the PEAR

    classes without needing to type in long, convoluted file paths.

    The Cache_Lite object can support multiple caches simultaneously, so long as every cache created has a

    unique identifier. In this case, Ive used the identifier "starwars" to uniquely distinguish the cache Ill beusing.

    Next, an object of the Cache_Lite class needs to be initialized, and assigned to a PHP variable.

    This variable, $objCache, now serves as the control point for cache manipulation.

    The constructor of the Cache_Lite class can be provided with an associative array containing

    configuration parameters; these parameters allow you to customize the behaviour of the cache. In the

    example above, this array contains two parameters, "cacheDir", which specifies the directory used by the

    cache, and "lifeTime", which specifies the period for which data should be cached, in seconds.

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    10/24

    ?>

    Note that the directory specified must already exist, or else the cache will simply not work.

    Once an instance of the Cache_Lite object has been created, the business logic to use it becomes fairly

    simple. The first step is to check if the required data already exists in the cache. If it doesnt, it should be

    generated from the original data source, and a copy saved to the cache for future use. If it does, you can do

    something useful with it - write it to a file, pipe it to an external program or - as Ive done here - simply

    output it to the screen for all to admire.

    Most of this logic is accomplished via the get() and save() methods of the Cache_Lite object. The get()

    method checks to see if the data exists in the cache and returns it if so, while the save() method saves data

    to the cache. The save() method accepts the data to be saved, together with a unique identifier, as input

    arguments; the get() method uses this identifier to find and retrieve the cached data.

    The steps above make up a fairly standard process for using the Cache_Lite class, and youll see them

    being repeated over and over again in subsequent examples as well.

    Printed from DevShed.com

    6

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    11/24

    In And Out

    The example you just saw cached the output of PHP statements. Its also possible to cache static HTML

    content, through creative use of PHPs output buffering functions. Consider the following example, which

    revises the code on the previous page to cache HTML markup instead of PHP command output:

    Do, or do not. There is no try.


    -- Yoda, Star Wars

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    12/24

    ob_end_flush();

    }

    ?>

    In this case, PHPs output buffering functions have been used to capture all the output generated

    subsequent to the call to ob_start(), and store this output in a buffer. Once the entire output has been

    captured, the ob_get_contents() function is used to retrieve the buffer contents to a variable. This variable

    (which now contains the entire HTML page) is then stored in the cache for future use. Finally, the

    ob_end_flush() function is used to end output buffering and send the contents of the buffer to the browser.

    Printed from DevShed.com

    8

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    13/24

    Different Strokes

    An alternative method to accomplish the task on the previous page lies with the Cache_Lite_Output()

    class, a subclass of the Cache_Lite class. This subclass (which internally uses output buffering) inherits all

    of the attributes of the parent class, and adds two methods to the parent class method collection: a start()method, which begins caching data, and an end() method, which marks the end of data caching.

    Consider the following variant of the example on the previosu page, which illustrates how this may be

    used:

    Do or do not. There is no try.


    -- Yoda, Star Wars

    Over here, if the call to start() - which is provided with a cache identifier - returns true, it implies that therequested data has already been cached, and the Cache_Lite_Output object takes care of printing the

    contents of the cache. If, however, the call to start() returns false, it implies that the data is not present in

    the cache, and so all subsequent output generated by the script will be cached, until the objects end()

    method is invoked.

    Printed from DevShed.com

    9

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    14/24

    Bits And Bytes

    Its also possible to use the Cache_Lite object to cache certain sections of a page, rather than the entire

    page - useful if some parts of the page are updated more frequently than others. This is accomplished by

    specifying a different cache identifier for each block of data that is to be cached, and using these differentidentifiers to retrieve data when needed. Data that is not to be cached (that is, data that is to be retrieved

    from source every time it is needed) will simply not be included in the call to the Cache_Lite objects

    save() method.

    Consider the following example, which demonstrates:

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    15/24

    // second data block

    // test if there is a valid cache for this block

    if ($data = $objCache->get("featured_character"))

    {

    // if so, display itecho $data;

    }

    else

    {

    // formulate and execute query

    $query = "SELECT char FROM characters ORDER BY RAND() LIMIT 1";

    $result = mysql_query($query) or die("Error in query: " .

    mysql_error());

    // get record

    $row = mysql_fetch_object($result);

    // display it

    echo $row->char;// and also cache it

    $objCache->save($row->char, "featured_character");

    }

    // close connection

    mysql_close($connection);

    ?>

    In this case, the code for the header and footer blocks is cached; however, the data in between the two is

    not. Note the use of two different cache identifiers in this example, one for each block.

    Printed from DevShed.com

    11

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    16/24

    Of Form And Function

    Just as you can cache HTML markup and PHP command output, its also possible to cache the output of

    user-defined functions with the Cache_Lite class...or, more precisely, with the Cache_Lite_Function

    subclass. This subclass inherits all the methods and properties of the parent Cache_Lite class, and adds anadditional one: the call() method, which is used to save the return value of a PHP function to the cache.

    Using the Cache_Lite_Function objects call() method is simplicity itself: the methods accepts the name of

    the function to be cached as its first argument, and input parameters to that function as additional

    arguments. It then first checks the cache to see if the function has been cached previously. If it has, the

    previous return value is retrieved without actually executing the function; if it has not, the function is

    executed (with appropriate arguments) and the result returned to the caller and simultaneously saved to the

    cache for future use.

    Heres a simple example which demonstrates how this works:

    And heres an example of the output:

    The cached time is 13:08:50. The real time is 13:11:40

    Printed from DevShed.com

    12

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    17/24

    As you might imagine, this class has the potential to do much more than

    simply confuse users in search of the time. Flip the page to see what I

    mean.

    Printed from DevShed.com

    13

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    18/24

    No News Is Good News

    Heres another, more realistic example, which caches a database result

    set and uses the cached set in order to reduce the time spent on

    executing subsequent queries for the same data. The result set isobtained via a function called get_headlines(), converted into a PHP

    array and cached using the call() method of the Cache_Lite_Function

    class.

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    19/24

    // iterate over return value and print elements

    echo "";

    foreach($data as $h)

    {

    echo "$h";}

    echo "";

    ?>

    Heres what the output looks like:

    Printed from DevShed.com

    15

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    20/24

    Cache Cow

    Now that you know the theory, lets wrap this tutorial up with a

    real-world example of how useful the Cache_Lite class can be in

    improving performance on your Web site. As you may (or may not) know,Amazon.com recently opened up their product catalog, allowing

    developers to create Amazon-backed online stores with their new AWS

    service. This service allows develoeprs to interact with Amazon.coms

    catalog and transaction system using SOAP, and it represents an

    important milestone in the progress of XML-based Web services.

    The only problem? Querying the AWS system, retrieving XML-encoded data

    and formatting it for use on a Web page is a complex process, one which

    can affect the performance of your store substantially. In order to

    compensate for this, clever developers can consider caching some of the

    AWS data on their local systems, reducing the need to query Amazon.com

    for every single request and thereby improving performance on their

    site.

    Heres the script,

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    21/24

    $proxy = $soapclient->getProxy();

    // set up an array containing input parameters to be

    // passed to the remote procedure

    $params = array(

    browse_node => 1000,page => 1,

    mode => books,

    tag => melonfire-20,

    type => lite,

    devtag => YOUR_TOKEN_HERE,

    sort => +salesrank

    );

    // invoke the method

    $result = $proxy->BrowseNodeSearchRequest($params);

    // check for errors

    if ($result[faultstring])

    {echo $result[faultstring];

    }

    else

    {

    // no errors?

    $total = $result[TotalResults];

    $items = $result[Details];

    // format and display the results

    ?>

    Bestsellers

    Browse the catalog below:

    Printed from DevShed.com

    17

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    22/24

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    23/24

    Im assuming here that you already know how to use AWS (in case you

    dont, flip the page for some links to tutorials that will teach you

    the basics, and remember that youll need a free AWS developer token

    for the script above to work) and instead will focus on the caching

    aspects of the system.

    Since this Web page contains intermingled HTML and PHP code, its

    convenient to use the Cache_Lite_Output class here. The first task,

    obviously, is to initialize and configure the cache; Ive set the cache

    to refresh itself at 30-minute intervals, since this seems like a

    reasonable period of time. Next, Ive used the start() method to see ifany data already exists in the cache, and display it if so.

    If no data exists, the NuSOAP PHP class is include()-d in the script, a

    SOAP client is instantiated, and a request is made to Amazon.com to

    obtain a list of bestsellers (node ID 100 in the AWS system). The

    response is then parsed and formatted into a Web page suitable for

    display; it is also simultaneously saved to the cache so that future

    requests for the same page can be served instantly, without having to

    query the AWS system each time. The end result: faster responses to

    user clicks, and an overall enhancement in user perception of your

    sites performance.

    Printed from DevShed.com

    19

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Caching With PHP Cache_Lite

    24/24

    Endgame

    And thats about all we have time for. In this article, I introduced

    you to the PEAR Cache_Lite class, a PHP class designed specifically to

    provide a robust caching mechanism for Web pages. I showed you how toconfigure the location and the lifetime of the cache, and demonstrated

    how to use the class to cache both static HTML content and dynamic PHP

    output. I also gave you a quick tour of the Cache_Lite class two

    variants, the Cache_Lite_Output and Cache_Lite_Function classes,

    illustrating how they could be used to cache blocks of output and

    function return values, respectively. Finally, I wrapped things up with

    a real-world example, showing you how a cache can make a substantial

    difference when dealing with complex, XML-based applications like

    Amazon Web Services.

    In case youd like to learn more about the topics discussed in this

    article, you should consider visiting the following links:

    Documentation for the PEAR Cache_Lite class, at

    http://pear.php.net/package-info.php?pacid=99

    phpCache, a lightweight alternative to Cache_Lite, at

    http://0x00.org/php/phpCache/, and a tutorial on how to use it, at

    http://www.sitepoint.com/article/685

    A comprehensive resource on the topic of Web caching, at

    http://www.web-caching.com/

    An article discussing the benefits of caching your Web content, at

    http://www.ariadne.ac.uk/issue4/caching/

    Using Amazon Web Services With PHP And SOAP, at

    http://www.melonfire.com/community/columns/trog/article.php?id=162

    Until next time...stay healthy!Note: Examples are illustrative only, and are not meant for a

    production environment. Melonfire provides no warranties or support for

    the source code described in this article. YMMV!

    http://www.ariadne.ac.uk/issue4/caching/http://www.ariadne.ac.uk/issue4/caching/
Embed Size (px)
Recommended