SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Level 8 Chinese guy Archbob's Avatar
    Join Date
    Sep 2001
    Location
    Somewhere in this vast universe
    Posts
    3,741
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Cache-ing in PHP

    I've never really looked at this before but how to you set something to save stuff off in cache in PHP to improve loading times. It is a server configuration or is there code to do it?

  2. #2
    SitePoint Wizard cranial-bore's Avatar
    Join Date
    Jan 2002
    Location
    Australia
    Posts
    2,634
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    code, based on object buffering.
    The first time "fresh" content is requested you build it as normal and display it, but you also capture a copy.
    The next time the same content is requested you can serve the content directly from cache without accessing the database or doing other processing.

    A ultra-simple procedural example might look like this:
    PHP Code:
    $cacheFile 'cache/article_list';

    //Serve from cache
    if(file_exists($cacheFile) AND $content file_get_contents($cacheFile)) exit($content);


    //Get fresh
    ob_start();

    //Access database, or otherwise build content
    echo 'I am the article list';

    //Save cache file
    $content ob_get_contents();
    ob_end_flush();
    file_put_contents($cacheFile$content); 
    It's obviously a good idea to wrap this functionality up into a class to make your code less repetitive.
    I think PEAR's got a good lite caching class, but I use one I wrote myself.

  3. #3
    SitePoint Addict
    Join Date
    Mar 2003
    Location
    In a house in the USA
    Posts
    293
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can also look into database caching as well. Using a database wrapper you can easily cache your data into files and then read back without having to write different code for each query.

    **Note: When caching a database you are just moving the load from one type of access to another. So your database server will get less requests but you will be accessing your filesystem a lot more. If you run a small site you may not need database caching.

    I have just taken a look at several php frameworks and found that CodeIgniter has an interesting database wrapper/caching system. (To bad it is still all PHP4)
    Daniel
    http://www.wlscripting.com - PHP Tutorials and code snippets
    Notepad++ Function List plugin tip - for PHP developers


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •