Recipe 11.6. Storing Arbitrary Data in Shared Memory


11.6.1. Problem

You want a chunk of data to be available to all web server processes through shared memory.

11.6.2. Solution

Use the pc_Shm class shown in Example 11-3. For example, to store a string in shared memory, used the pc_Shm::save( ) method, which accepts a key/value pair:

<?php $shm = new pc_Shm(); $secret_code = 'land shark'; $shm->save('mysecret', $secret_code); ?>

Another process can then access that data from shared memory with the pc_Shm::fetch( ) method:

<?php $shm = new pc_Shm(); print $shm->fetch('mysecret'); ?>

11.6.3. Discussion

Occasionally there are times when you want to cache a value or set of values in shared memory for rapid retrieval. If your web server is busy with disk I/O, it may make sense to leverage the shmop functions to achieve greater performance with storage and retrieval of information in that cache.

The pc_Shm class has two convenient methods, pc_Shm::fetch( ) and pc_Shm::save( ), which abstract away the need to set memory addresses or explictly open and close the shared memory segments.

It's important to remember that, unlike setting a key/value pair in a regular PHP array, the shmop functions need to allocate a specific amount of space that the data stored there is expected to consume. The pc_Shm class allocates 16k for each value by default. If data you need to store is larger than 16k, you need to increase the amount of space the shmop functions should reserve. For example:

<?php $shm = new pc_Shm(); $shm->setSize(24576); // 24k $shm->save('longstring', 'Lorem ipsum pri eu simul nominati...'); ?>

11.6.4. See Also

Recipe 11.5 and Recipe 5.6; the Memcache section of the PHP online manual at http://www.php.net/memcache. Memcache is a very fast and efficient alternative to the shmop functions. More information about memcache can be found at http://www.danga.com/memcached/. Also, the PECL apc module (http://pecl.php.net/apc) offers functions for storing data in shared memory.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net