Example of implementing memcache cache using php

Source: Internet
Author: User
Shared memory is an effective way to exchange data between applications on the same machine. This article describes how to implement memcache cache in php. For more information, see use memcache.

Overview

Shared memory is an effective way to exchange data between applications on the same machine. A process can create a memory segment that can be accessed by other processes as long as it is assigned the correct permissions. Each memory segment has a unique ID (called shmid) that points to a physical memory area where other processes can operate on it. After creating and providing appropriate permissions, other processes on the same machine can operate on these memory segments: read, write, and delete.

This indicates that applications written in C can be used with other languages (such as Java™Or PHP. All of them can share information as long as they can access and understand this information. Shared content is widely used in most languages. Therefore, access is not a problem. To understand the information, we can use a standard format, such as XML or JSON.
Shared memory is a fast way to exchange data between processes. it is mainly because data is transmitted after the memory segment is created and does not involve the kernel. This method is often called inter-process communication (IPC ). Other IPC methods include pipelines, message queues, RPC, and sockets. This ability to exchange data quickly and reliably between applications is useful when using an ecosystem of applications that need to communicate with each other. Depending on the size of the ecosystem, common methods for exchanging information between applications using databases often lead to slow queries or even I/O blocking. Using shared memory, without I/O will slow down the development progress.

The proposal in this article is very simple. learn how to use PHP to create and operate shared memory segments and use them to store datasets that can be used by other applications. Even if there is no plan to use shared memory to exchange data, it has many advantages in itself, because it enables applications to stay away from I/O problems. Directly storing datasets in memory has many advantages, from Web service data cache to session sharing. It is a very useful concept that every PHP developer should know.
Shared memory and PHP

PHP has rich available extensions, and the same is true for shared memory. With some shared functions, developers can easily operate memory segments without installing any extensions.

Create memory segments

The shared memory function is similar to the file operation function, but does not need to process a stream. you will process a shared memory access ID. The first example is the shmop_open function, which allows you to open an existing memory segment or create a new memory segment. This function is very similar to the classic fopen function, which opens the stream for file operations and returns a resource for other functions that want to read or write the open stream. Let's take a look at shmop_open in listing 1.

Listing 1. shmop_open function

The code is as follows:
$ Systemid = 864; // System ID for the shared memory segment
$ Mode = "c"; // Access mode
$ Permissions = 0755; // Permissions for the shared memory segment
$ Size = 1024; // Size, in bytes, of the segment

$ Shmid = shmop_open ($ systemid, $ mode, $ permissions, $ size );

?>

The first thing that appears in this function is the system ID parameter. This is the number that identifies the shared memory segment in the system. The second parameter is the access mode, which is very similar to the access mode of the fopen function. You can access a memory segment in four different modes:

• Mode "a", which allows you to access read-only memory segments
• Mode "w", which allows you to access read/write memory segments
• Mode "c", which creates a new memory segment, or if the memory segment already exists, try to open it for read/write
• Mode "n", which creates a new memory segment. if this memory segment already exists, it will fail
The third parameter is the permission of the memory segment. You must provide an octal value here.

The fourth parameter provides the memory segment size, in bytes. Before writing a memory segment, you must allocate the appropriate number of bytes on it.

Note that this function returns an ID number, which can be used by other functions to operate the shared memory segment. This ID is the shared memory access ID. Unlike the system ID, it is passed as a parameter. Do not confuse the two. If it fails, shmop_open returns FALSE.

Write data to memory segments

Use the shmop_write function to write data to shared memory blocks. This function is easy to use. it only accepts three parameters, as shown in listing 2.

Listing 2. using shmop_write to write data to shared memory blocks

The code is as follows:

$ Shmid = shmop_open (864, 'C', 0755,102 4 );
Shmop_write ($ shmid, "Hello World! ", 0 );

?>

This function is similar to the fwrite function, which has two parameters: Open Stream resource (returned by fopen) and data you want to write. The shmop_write function also executes this task.

The first parameter is the ID returned by shmop_open, which identifies the shared memory block you operate on. The second parameter is the data you want to store, and the third parameter is the location where you want to start writing. By default, we always use 0 to indicate the start position of the write operation. Note that this function returns FALSE if it fails and the number of bytes written when it succeeds.


Read data from memory segments
It is easy to read data from the shared memory segment. You only need an open memory segment and the shmop_read function. This function accepts some parameters and works like fread. See listing 3 to read the content of a PHP file.

Listing 3. using shmop_read to read the content of a file

The code is as follows:

$ Stream = fopen('file.txt ', 'R + ');
Fwrite ($ stream, "Hello World! ");
Echo fread ($ stream, 11 );

?>

The process of reading shared memory segments is similar to this, as shown in listing 4:

Listing 4. reading shared memory segments

The code is as follows:

$ Shmid = shmop_open (864, 'C', 0755,102 4 );
Shmop_write ($ shmid, "Hello World! ", 0 );
Echo shmop_read ($ shmid, 0, 11 );

?>

Pay attention to the parameters here. The shmop_read function will accept the ID returned by shmop_open. we know it, but it also accepts two other parameters. The second parameter is the location you want to read from the memory segment, and the third parameter is the number of bytes you want to read. The second parameter can always be 0, indicating the beginning of the data, but the third parameter may be faulty because we do not know how many bytes we want to read.

This is very similar to our behavior in the fread function. this function accepts two parameters: the opened stream resource (returned by fopen) and the number of bytes you want to read from the stream. Use the filesize function (which returns the number of bytes in a file) to completely read it.

Fortunately, when using shared memory segments, the shmop_size function returns the size (in bytes) of a memory segment, similar to the filesize function. See listing 5.

Listing 5. the size of the memory segment returned by the shmop_size function, in bytes

The code is as follows:

$ Shmid = shmop_open (864, 'C', 0755,102 4 );
Shmop_write ($ shmid, "Hello World! ", 0 );

$ Size = shmop_size ($ shmid );
Echo shmop_read ($ shmid, 0, $ size );

?>

Back to top

Delete memory segments
We learned how to open, write, and read shared memory segments. To complete our CRUD class, we also need to learn how to delete the memory segment. This task can be easily completed using the shmop_delete function. this function only accepts one parameter: the shared memory ID we want to delete.

Listing 6. marked the memory segment to be deleted by shmop_delete

The code is as follows:

$ Shmid = shmop_open (864, 'C', 0755,102 4 );
Shmop_write ($ shmid, "Hello World! ", 0 );
Shmop_delete ($ shmid );

?>

This does not actually delete the memory segment. It marks the memory segment as deleted because it cannot be deleted when other processes are using it. The shmop_delete function marks the memory field as deleted to prevent any other process from opening it. To delete it, we need to disable this memory segment.

Disable memory segments

Opening a shared memory segment will be "appended" to it. After attaching this memory segment, we can read and write it, but after the operation is completed, we must remove it from it. This is done using the shmop_close function in listing 7.

This is very similar to the fclose function when processing files. When you open a stream containing a file and read or write data in it, you must disable it. Otherwise, the stream will be locked.

Listing 7. use shmop_close to separate a memory segment

The code is as follows:

$ Shmid = shmop_open (864, 'C', 0755,102 4 );
Shmop_write ($ shmid, "Hello World! ", 0 );
Shmop_delete ($ shmid );
Shmop_close ($ shmid );

?>

Use Shared memory as a storage option
With the basic knowledge of basic CRUD operations in shared memory and shared memory segments, it is time to apply this knowledge. We can use shared memory as a unique storage option to provide fast read/write operations and process interoperability. For Web applications, this means:

• Cache storage (database query, Web Service data, and external data)
• Session storage
• Data exchange between applications
Before proceeding, I would like to introduce a small library named SimpleSHM. SimpleSHM is a small abstraction layer used to operate shared memory in PHP. it supports easy operation of memory segments in an object-oriented manner. When writing small applications that use shared memory for storage, this library can help create very concise code. For more information about SimpleSHM, visit the GitHub page.

You can use three methods for processing: read, write, and delete. Simply instantiate an object from this class to control the open shared memory segments. Listing 8 shows the basic usage.

Listing 8. basic use of SimpleSHM

The code is as follows:

$ Memory = new SimpleSHM;
$ Memory-> write ('sample ');
Echo $ memory-> read ();

?>

Note that no ID is passed for this class. If no ID is passed, it selects a random number and opens the new memory segment of the number. You can pass a number as a parameter for the constructor to open an existing memory segment or create a memory segment with a specific ID, as shown in listing 9.

Listing 9. open a specific memory segment

The code is as follows:

$ 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 cancel the setting object and separate it from the memory segment. We call this "SimpleSHM 101 ". Now let's use this method for more advanced purposes: using shared memory as storage. Serialization is required for storing datasets because arrays or objects cannot be stored in memory. Although JSON is used for serialization, other methods (such as XML or built-in PHP Serialization) are sufficient. Listing 10 provides an example.

Listing 10. using shared memory as storage

The code is as follows:

Require ('simpleshm. class. php ');

$ Results = array (
'User' => 'John ',
'Password' => '123 ',
'Posts' => array ('My name is John', 'My name is not John ')
);

$ Data = json_encode ($ results );

$ Memory = new SimpleSHM;
$ Memory-> write ($ data );
$ Storedarray = json_decode ($ memory-> read ());

Print_r ($ storedarray );

?>

We successfully serialize an array into a JSON string, store it in a shared memory block, read data from it, serialize the JSON string, and display the stored array. This looks simple, but imagine the possibility of this code snippet. You can use it to store Web service requests, database queries, or even template engine cache results. Reading and Writing in the memory will provide higher performance than reading and writing in the disk.

This storage technology is not only useful for caching, but also for data exchange between applications, as long as the data is stored in a format that can be read at both ends. Do not underestimate the power of sharing in Web applications. This storage can be cleverly implemented in many different ways. The only restriction is the developer's creativity and skills.

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.