Steve
Steve

Reputation: 3046

Acceptable Memcached usage

I'm having a bit of trouble with Memcached.

I have this code below:

if(!$Z->get('user')) {
    $Z->set('user', $hs->load_hs_main($_GET['from'], $_GET['table']));
}

$je = $Z->get('user') ? $Z->get('user') : $hs->load_hs_main($_GET['from'], $_GET['table']);

What $Z->get('user') and $je are supposed to be is a MySQLi result object. This gives weird effects like print_r not functioning and it just doesn't look right.

I want to check if an object exists that was created by memcached and use it if it exists.. but if it doesn't, set it.

Upvotes: 1

Views: 101

Answers (2)

johannes
johannes

Reputation: 15969

In general you can't store objects of "internal" classes in memcache. Those objects contain data which can't be serialized. You have to fetch the data from the result object and store it in a PHP array. Then you can store that array in memcache.

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318508

The correct way to get an item from cache or create/load it from somewhere else if it doesn't exist is this:

$user = $Z->get('user'); // get it from cache, returns falsy value if not found
if(!$user) { // not found
    $user = $hs->load_hs_main(...); // load the element from somewhere else
    $Z->set('user', $user); // cache it
}
// here $user always exists

Upvotes: 3

Related Questions