Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hashmap in Application context php

I am trying to implement a hashmap (associative array in PHP) in PHP which is available application wide i.e store it in application context, it should not be lost when the program ends. How I can I achieve this in PHP?

Thanks,

like image 866
cldy1020 Avatar asked Nov 03 '22 23:11

cldy1020


1 Answers

If you are using Zend's version of php, it's easy.
You do not need to serialize your data.
Only contents can be cached. Resources such as filehandles can not. To store true/false, use 1,0 so you can differentiate a cache failure from a result with ===.

Store:

zend_shm_cache_store('cache_namespace::this_cache_name',$any_variable,$expire_in_seconds);

Retrieve:

$any_variable = zend_shm_cache_fetch('cache_namespace::this_cache_name');

if ( $any_variable === false ) {
    # cache was expired or did not exist.
}

For long lived data you can use:

zend_disk_cache_store();zend_disk_cache_fetch();

For those without zend, the corresponding APC versions of the above:

Store:

apc_store('cache_name',$any_variable,$expire_in_seconds);

Retrieve:

$any_variable = apc_fetch('cache_name');

if ( $any_variable === false ) {
    # cache was expired or did not exist.
}

Never used any of the other methods mentioned. If you don't have shared memory available to you, you could serialize/unserialize the data to disk. Of course shared memory is much faster and the nice thing about zend is it handles concurrency issues for you and allows namespaces:

Store:

file_put_contents('/tmp/some_filename',serialize($any_variable));

Retrieve:

$any_variable = unserialize(file_get_contents('/tmp/some_filename') );

Edit: To handle concurrency issues yourself, I think the easiest way would be to use locking. I can still see the possiblity of a race condition in this psuedo code between lock exists and get lock, but you get the point.

Psuedo code:

while ( lock exists ) {
    microsleep;
}
get lock.
check we got lock.
write value.
release lock.
like image 149
Daren Schwenke Avatar answered Nov 14 '22 01:11

Daren Schwenke