PHP Operation shared Memory Shmop class and simple code to use test

Source: Internet
Author: User
This article mainly introduces the PHP operation shared memory Shmop class and simple use of test code, has a certain reference value, now share to everyone, the need for friends can refer to

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 object Namespace Simple\shm;class block{/** * holds the system ID for the shared memory Block * * @v    AR int * @access protected */protected $id; /** * holds the shared memory block ID returned by Shmop_open * * @var int * @access protected */P    Rotected $shmid; /** * holds the default permission (octal) that'll be used in created memory blocks * * @var int * @acce    SS protected */protected $perms = 0644; /** * Shared memory block instantiation * * In the constructor we'll check if the block we ' re going to Manipul ATE * 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 */P        ublic function __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 */protected function Generateid () {$id = ft        Ok (__file__, "B");    return $id;  }/** * Checks If a shared memory block with the provided ID exists or no * in order to check for shared Memory 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 */public function 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 create 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 to write into the shared memory block */P        ublic function 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 */        Public function read () {$size = Shmop_size ($this->shmid);        $data = Shmop_read ($this->shmid, 0, $size);    return $data;        }/** * Mark a shared memory block for deletion * * @access public */Public Function Delete () {    Shmop_delete ($this->shmid);        }/** * Gets the current shared memory block ID * * @access public */Public function getId () {    return $this->id; }/** * Gets the current shared memory block permissions * * @access public */Public function Getpe    Rmissions () {return $this->perms;     }/** * Sets the default permission (octal) that would be used on created memory blocks * * @access public * @param string $perms Permissions, in octal form */Public Function SetPermissions ($perms) {$This->perms = $perms; }/** * Closes the shared memory block and stops manipulation * * @access public */Public function    __destruct () {shmop_close ($this->shmid); }}
<?php//test using code namespace Simple\shm\test;use simple\shm\block;class Blocktest extends \phpunit_framework_testcase{        Public Function Testiscreatingnewblock () {$memory = new Block;        $this->assertinstanceof (' Simple\\shm\\block ', $memory);        $memory->write (' Sample ');        $data = $memory->read ();    $this->assertequals (' Sample ', $data);        } public Function Testiscreatingnewblockwithid () {$memory = new Block (897);        $this->assertinstanceof (' Simple\\shm\\block ', $memory);        $this->assertequals (897, $memory->getid ());        $memory->write (' Sample 2 ');        $data = $memory->read ();    $this->assertequals (' Sample 2 ', $data);        } public Function Testismarkingblockfordeletion () {$memory = new Block (897);        $memory->delete ();        $data = $memory->read ();    $this->assertequals (' Sample 2 ', $data); } public Function Testispersistingnewblockwithoutid () {$meMory = new Block;        $this->assertinstanceof (' Simple\\shm\\block ', $memory);        $memory->write (' Sample 3 ');        Unset ($memory);        $memory = new Block;        $data = $memory->read ();    $this->assertequals (' Sample 3 ', $data); }}

Additional Instructions

<?php $memory = new Simpleshm; $memory->write (' Sample '); Echo $memory->read ();?>

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->read ();?>

The Magic Method __destructor is responsible for calling Shmop_close on the memory segment 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 ' = ' = ', '    My name is John ', ' My n Ame is not John ')); $data = Json_encode ($results); $memory = new Simpleshm; $memory->write ($data); $storedarray = Json_decode ($memory->read ()); 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.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.