PHP Operation shared Memory Shmop class and simple use Test (code)

Source: Internet
Author: User

SIMPLESHM is a small abstraction layer that uses PHP to manipulate shared memory, enabling easy manipulation of memory segments in an object-oriented manner. When writing small applications that use shared memory for storage, this library helps to create very concise code. You can use 3 methods for processing: Read, write, and delete. By simply instantiating an object from the class, you can control the open shared memory segment.

Class object and test code

<?PHP//Class ObjectnamespaceSimple\shm;classblock{/** * holds the system ID for the shared memory block * * @var int * @access protected*/    protected$id; /** * holds the shared memory block ID returned by Shmop_open * * @var int * @access protected*/    protected$shmid; /** * holds the default permission (octal) that would be a used in created memory blocks * * @var int * @ac Cess protected*/    protected$perms =0644; /** Shared memory block instantiation * * In the constructor we'll check if the block we ' re going to Manip Ulate * already exists or needs to be created.     If it exists, let ' s open it. * * @access public * @param string $id (optional) ID of the shared memory block want to manipulate*/     Publicfunction __construct ($id =NULL)    {        if($id = = =NULL) {            $ This->id = $ This-Generateid (); } Else {            $ This->id =$id; }        if($ This->exists ($ This-ID)) {$ This->shmid = Shmop_open ($ This->id,"W",0,0); }    }    /** * generates a random ID for a shared memory block * * @access protected * @return int System V IPC Key generated from pathname and a project identifier*/    protectedfunction Generateid () {$id= Ftok (__file__,"b"); return$id; }    /** * Checks If a shared memory block with the provided ID exists or not * * In order to check for shared me Mory existance, we have to open it with * reading access.     If it doesn ' t exist, warnings'll is cast, therefore we * suppress those with the @ operator. * * @access public * @param string $id ID of the shared memory block want to check * @return Boolean True If the block exists, false if it doesn ' t*/     Publicfunction exists ($id) {$status= @shmop_open ($id,"a",0,0); return$status; }    /** * writes on a shared memory block * * First we check for the block existance, and if it doesn ' t, we ' ll C Reate it. Now, if the-the * block already exists, we need to delete it and create it again with a new byte allocation that * mat Ches the size of the data, we want to write there.     We mark for deletion, close the semaphore * and create it again. * * @access public * @param string $data The data so you wan ' t-write into the shared memory block*/     Publicfunction Write ($data) {$size= Mb_strlen ($data,'UTF-8'); if($ This->exists ($ This-ID) {shmop_delete ($ This-shmid); Shmop_close ($ This-shmid); $ This->shmid = Shmop_open ($ This->id,"C", $ This-perms, $size); Shmop_write ($ This->shmid, $data,0); } Else {            $ This->shmid = Shmop_open ($ This->id,"C", $ This-perms, $size); Shmop_write ($ This->shmid, $data,0); }    }    /** * Reads from a shared memory block * * @access public * @return string The data read from the shared Memory Block*/     Publicfunction Read () {$size= Shmop_size ($ This-shmid); $data= Shmop_read ($ This->shmid,0, $size); return$data; }    /** Mark a shared memory block for deletion * * @access Public*/     Publicfunction Delete () {Shmop_delete ($ This-shmid); }    /** * Gets the current shared memory block ID * * @access Public*/     Publicfunction GetId () {return$ This-ID; }    /** * Gets the current shared memory block permissions * * @access Public*/     Publicfunction GetPermissions () {return$ This-perms; }    /** * Sets the default permission (octal) that would be is used in created memory blocks * * @access public * @param string $perms Permissions, in octal form*/     Publicfunction SetPermissions ($perms) {$ This->perms =$perms; }    /** * closes the shared memory block and stops manipulation * * @access Public*/     Publicfunction __destruct () {shmop_close ($ This-shmid); }}
<?PHP//test Using CodenamespaceSimple\shm\test;use Simple\shm\block;classBlocktest extends \phpunit_framework_testcase{ Publicfunction Testiscreatingnewblock () {$memory=NewBlock; $ This->assertinstanceof ('Simple\\shm\\block', $memory); $memory->write ('Sample'); $data= $memoryread (); $ This->assertequals ('Sample', $data); }     Publicfunction Testiscreatingnewblockwithid () {$memory=NewBlock (897); $ This->assertinstanceof ('Simple\\shm\\block', $memory); $ This->assertequals (897, $memorygetId ()); $memory->write ('Sample 2'); $data= $memoryread (); $ This->assertequals ('Sample 2', $data); }     Publicfunction Testismarkingblockfordeletion () {$memory=NewBlock (897); $memory-Delete (); $data= $memoryread (); $ This->assertequals ('Sample 2', $data); }     Publicfunction Testispersistingnewblockwithoutid () {$memory=NewBlock; $ This->assertinstanceof ('Simple\\shm\\block', $memory); $memory->write ('Sample 3');        Unset ($memory); $memory=NewBlock; $data= $memoryread (); $ This->assertequals ('Sample 3', $data); }}

Additional Instructions

<?  new  simpleshm; $memory->write ('Sample'); Echo $memory ?>

Note that there is no ID passed for the class in the code above. If no pass ID is passed, it randomly selects a number and opens the new memory segment for that number. We can pass a number as a parameter for the constructor to open an existing memory segment, or to create a memory segment with a specific ID, as follows

<? PHP $ New New SIMPLESHM (897); $new->write ('Sample'); echo $ ?>, new

The Magic Method __destructor is responsible for calling on the memory segment shmop_close to de-set the object to be detached from the memory segment. We refer to this as "Simpleshm 101". Now let's use this method for more advanced purposes: using shared memory as storage. The storage dataset needs to be serialized because the array or object cannot be stored in memory. Although JSON is used here to serialize, any other method, such as XML or the built-in PHP serialization functionality, is sufficient. As follows

<?php require ('SimpleSHM.class.php'); $results=Array ('User'='John',    'Password'='123456',    'posts'= = Array ('My name is John','My name is not John')); $data=Json_encode ($results); $memory=NewSimpleshm; $memory-write ($data); $storedarray= Json_decode ($memoryread ()); Print_r ($storedarray); ?>

We successfully serialized an array into a JSON string, storing it in a shared memory block, reading the data from it, serializing the JSON string, and displaying the stored array. This may seem simple, but imagine the possibilities that this code snippet brings. You can use it to store the results of a WEB service request, a database query, or even a template engine cache. Read and write in memory will bring higher performance than read and write on disk.

Using this storage technology is useful not only for caching, but also for exchanging data between applications, as long as the data is stored in a readable format on both ends. Do not underestimate the power of WEB applications that exist within a share. This kind of storage can be cleverly implemented in many different ways, with the only limitation being the developer's creativity and skills.

PHP Operation shared Memory Shmop class and simple use Test (code)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.