php implementation memcache cache example tutorial

  • 2020-12-05 17:08:22
  • OfStack

An overview of the

Shared memory is an efficient 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 allocates the correct permissions. Each memory segment has a 1-only ID (called shmid), which points to a physical memory region where other processes can manipulate it. Once the appropriate permissions have been created and provided, other processes on the same machine can operate on these memory segments: read, write, and delete.

This indicates that applications written in the C language can work with other languages (e.g. Java™ Applications written by PHP) share information. They can all share information as long as they have access to and understand it. Shared memory is widely used in implementations for most languages, so access should not be a problem. To understand the information, we can use one standard format, such as XML or JSON.
The use of shared memory is a fast way to exchange data between processes, mainly because passing data after creating memory segments does not involve the kernel. This approach is often referred to as interprocess communication (IPC). Other IPC methods include pipes, message queues, RPC, and sockets. This ability to exchange data quickly and reliably between applications is useful when using ecosystems that require applications to communicate with each other. Depending on the size of the ecosystem, the common approach of using a database to exchange information between applications often leads to slow queries or even I/O blocking. With shared memory, I/O does not slow developers down.

The proposal in this article is very simple: learn how to use PHP to create and manipulate shared memory segments and use them to store data sets that can be used by other applications. Even if there is no plan to swap data using shared memory, it has many benefits in itself, as it enables applications to stay away from I/O issues. Storing data sets directly in memory has many advantages, from Web service data caching to session sharing. It is a very useful concept that every PHP developer should know.
Shared memory and PHP

PHP has a wealth of extensions available, as well as shared memory. Using some shared functions, developers can easily manipulate memory segments without installing any extensions.

Create memory segment

The shared memory function is similar to the file manipulation function, but instead of dealing with 1 stream, you will deal with 1 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 one. This function is very similar to the classic fopen function, which opens a stream for file manipulation and returns a resource for other functions that want to read or write to the open stream. Let's look at shmop_open in Listing 1.

Listing 1. shmop_open function


<?php
$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 argument 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:

The & # 8226; Mode "a", which allows you to access read-only memory segments
The & # 8226; Mode "w", which allows you to access read-write memory segments
The & # 8226; Mode "c", which creates a new memory segment, or if the segment already exists, try opening it for read and write
The & # 8226; Mode "n", which creates a new memory segment that fails if it already exists
The third parameter is the permission of the memory segment. You must provide a base 8 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 top of it.

Note that this function returns an ID number that other functions can use to manipulate the shared memory segment. This ID is shared memory access ID and, unlike system ID, is passed as a parameter. Be careful not to confuse the two. On failure, shmop_open returns FALSE.

Writes data to a memory segment

Use the shmop_write function to write data to the shared memory block. This function is simple to use; it takes only three arguments, as shown in Listing 2.

Listing 2. Write data to the shared memory block using shmop_write


<?php
$shmid = shmop_open(864, 'c', 0755, 1024);
shmop_write($shmid, "Hello World!", 0);
?>
 

This function is similar to the fwrite function, which takes two arguments: the open stream resource (returned by fopen) and the data you want to write. The shmop_write function also performs this task.

The first parameter is ID returned by shmop_open, which identifies the shared memory block you are operating on. The second parameter is the data you want to store, and the final third parameter is where you want to start writing. By default, we always use 0 to indicate where to start writing. Note that this function returns FALSE on failure and the number of bytes written on success.


Reads data from memory segments
Reading data from a shared memory segment is simple. All you need is an open memory segment and the shmop_read function. This function takes 1 argument and works like fread. See Listing 3 to read the contents of an PHP file.

Listing 3. Using shmop_read to read the contents of a file


<?php
$stream = fopen('file.txt', 'r+');
fwrite($stream, "Hello World!");
echo fread($stream, 11);
?>
 

The process of reading the contents of the shared memory segment is similar, as shown in Listing 4:

Listing 4. Reading the contents of the shared memory segment


<?php
$shmid = shmop_open(864, 'c', 0755, 1024);
shmop_write($shmid, "Hello World!", 0);
echo shmop_read($shmid, 0, 11);
?>
 

Please note the parameters here. The shmop_read function will take ID returned by shmop_open, which we already know, but it also takes two more arguments. 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 argument can always be 0, representing the beginning of the data, but the third argument can be problematic because we don't know how many bytes we want to read.

This is very similar to what we did in the fread function, which takes two arguments: the open 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 read it in its entirety.

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

Listing 5. The shmop_size function returns the memory segment size in bytes


<?php
$shmid = shmop_open(864, 'c', 0755, 1024);
shmop_write($shmid, "Hello World!", 0);
$size = shmop_size($shmid);
echo shmop_read($shmid, 0, $size);
?>

Back to the first page

Delete memory segment
We learned how to open, write, and read shared memory segments. To complete our CRUD class, we also need to learn how to delete segments of memory. This can be done easily using the shmop_delete function, which takes just one argument: the shared memory ID that we want to remove.

Listing 6. shmop_delete marks the segment of memory to be deleted


<?php
$shmid = shmop_open(864, 'c', 0755, 1024);
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 the shared memory segment cannot be deleted while another process is using it. The shmop_delete function marks the memory segment as removed, preventing any other process from opening it. To delete it, we need to close the memory segment.

Close memory segment

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

This is very similar to the fclose function when working with files. After opening a stream containing 1 file and reading or writing data in it, we must close it or a lock will occur.

Listing 7. Use shmop_close to separate from a memory segment


<?php
$shmid = shmop_open(864, 'c', 0755, 1024);
shmop_write($shmid, "Hello World!", 0);
shmop_delete($shmid);
shmop_close($shmid);
?>
 

Use shared memory as a storage option
With a basic knowledge of shared memory and basic CRUD operations on shared memory segments, it's time to apply this knowledge. We can use shared memory as a unique storage option that provides advantages such as fast read/write operations and process interoperability. For the Web application, this means:

The & # 8226; Cache storage (database queries, Web service data, external data)
The & # 8226; The session storage
The & # 8226; Data exchange between applications
Before moving on, I'd like to introduce a small library called SimpleSHM. SimpleSHM is a small abstraction layer that uses PHP to manipulate shared memory, enabling easy manipulation of memory segments in an object-oriented manner. This library helps create very concise code when writing small applications that use shared memory for storage. To learn more about SimpleSHM, visit the GitHub page.

You can do this in three ways: read, write, and delete. By simply instantiating 1 object from this class, you can control the open shared memory segment. Listing 8 shows the basic use.

Listing 8. SimpleSHM basic uses


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

Note that there is no ID passed for this class. If ID is not passed, it randomly selects a number and opens a new memory segment with that number. We can pass a number as an argument for the constructor to open an existing segment, or we can create a segment with a specific ID, as shown in Listing 9.

Listing 9. Open a specific memory segment


<?php
$new = new SimpleSHM(897);
$new->write('Sample');
echo $new->read();
?>
 

___ The magic method with ES219en is responsible for calling shmop_close on the memory segment to unset the object and separate it from the memory segment. We call this "SimpleSHM 101". Now let's use this method for a more advanced purpose: using shared memory as storage. Storing data sets requires serialization because arrays or objects cannot be stored in memory. Although JSON is used here for serialization, any other method (such as XML or the built-in PHP serialization feature) is sufficient. Listing 10 shows an example.

Listing 10. Using shared memory for storage


<?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 = new SimpleSHM;
$memory->write($data);
$storedarray = json_decode($memory->read());
print_r($storedarray);
?>
 

We successfully serialized an array to an JSON string, stored it in a shared memory block, read the data from it, serialized the JSON string, and displayed the stored array. This seems simple enough, but imagine the possibilities that this snippet brings. You can use it to store Web service requests, database queries, or even results cached by the template engine. Reading and writing in memory results in better performance than reading and writing on disk.

Using this storage technique is useful not only for caching, but also for data exchange between applications, as long as the data is stored in a format that is readable by both ends. Don't underestimate the power of shared memory in Web applications. There are many different ways to implement this storage smartly, but the limit is the creativity and skill of the developer


Related articles: