5

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,

cldy1020
  • 711
  • 2
  • 9
  • 15
  • 1
    PHP itself has no 'application context'. There are workarounds (namely storing stuff in files or shared memory), but otherwise, nothing survives at the end of the execution of a PHP script. – zneak May 30 '12 at 18:08

2 Answers2

1

You can use APC or similars for this, the data you put there will be available in shared memory.

Bare in mind that this will not persist between server restarts of course.

Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • Thanks, What are the major differences between [APC](http://www.php.net/manual/en/book.apc.php) and [shared memory](http://www.php.net/manual/en/ref.shmop.php) ? – cldy1020 May 31 '12 at 19:11
1

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.
Daren Schwenke
  • 5,428
  • 3
  • 29
  • 34