php – Cache or store in session?-ThrowExceptions

Exception or error:

I have a page that has quite a lot of data loading from my db. I’d like to speed-up loading time. I already cache query, but still the loading time is longer than I’d like it to be.

Is it possible to render a table with data and store it in a session to load on every new page refresh? I was even thinking of putting it in an external text file using ob_start();

What’s the best way to handle it?

How to solve:

Storing it in sessions is probably not the best idea, when you add data to a session (by default) the data is written to a file on the OS, usually in /tmp/ which means you’re going to be hitting the disk quite a lot and storing just as much data.

If the data is not user specific then you could store it on disk, or in memory – (see: php.net/apc)

If the data is user specific, I recommend storing it in a distributed cache, such as Memcached (memcached.org) PHP has a library you can enable (php.net/memcached)

(by user specific I mean data like a users transactions, items, shopping cart, etc)

The logic is basically the same for any method you choose:

Memcached, user specific data example:

<?php

$memcached = new Memcached();
$data = $memcached->get('shopping-cart_' . $user_id);

if (!$data) {
    $sql = $db->query("..");
    $data = array();
    while($row = $query->fetch_assoc()) {
        $data[] = $row;
    } 
    $memcached->set('shopping-cart_' . $user_id, $data);
} 
?>
<table>
<?php 
foreach ($data as $item) {
    echo '<tr><td>' . $item['name'] .' </td></tr>';
}
?>
</table>

Global data (not user specific)

<?php
$cache_file = '/cached/pricing-structure.something';

if (file_exists($cache_file)) {
    echo $cache_file;
} else {
    // heavy query here 
    $h = fopen('/cached/pricing-structure.something', 'w+');
    fwrite($h, $data_from_query);
    fclose($h);
}

Answer´╝Ü

If you are doing caching on a single web server (as opposed to multiple distributed servers), PHP APC is a very easy-to-use solution. It is an in-memory cache, similar to memcache, but runs locally. I would avoid storing any significant amount of data in session.

APC is a PECL extension and can be installed with the command

pecl install apc

You may need to enable it in your php.ini.

Leave a Reply

Your email address will not be published. Required fields are marked *