php操作共享内存shmop类及简单使用测试(代码)-php教程

资源魔 31 0
SimpleSHM 是一个较小的形象层,用于应用 PHP 操作同享内存,支持以一种面向工具的形式轻松操作内存段。正在编写应用同享内存进行存储的小型使用顺序时,这个库可协助创立十分简约的代码。能够应用 3 个办法进行解决:读、写以及删除了。从该类中简略地实例化一个工具,能够管制关上的同享内存段。

类工具以及测试代码

<?php
//类工具
namespace Simple\SHM;
class Block
{
    /**
     * 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 will be used in created memory blocks
     *
     * @var int
     * @access protected
     */
    protected $perms = 0644;
    /**
     * Shared memory block instantiation
     *
     * In the constructor we'll check if the block we're going to manipulate
     * 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 you want to manipulate
     */
    public 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 = ftok(__FILE__, "b");
        return $id;
    }
    /**
     * Checks if a shared memory block with the provided id exists or not
     *
     * In order to check for shared memory existance, we have to open it with
     * reading access. If it doesn't exist, warnings will be cast, therefore we
     * suppress those with the @ operator.
     *
     * @access public
     * @param string $id ID of the shared memory block you 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
     * block already exists, we need to delete it and create it again with a new byte allocation that
     * matches the size of the data that we want to write there. We mark for deletion,  close the semaphore
     * and create it again.
     *
     * @access public
     * @param string $data The data that you wan't to write into the shared memory block
     */
    public 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 getPermissions()
    {
        return $this->perms;
    }
    /**
     * Sets the default permission (octal) that will be used in 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
//测试应用代码
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);
    }
}

额定阐明

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

请留意,下面代码里不为该类通报一个 ID。假如不通报 ID,它将随机抉择一个编号并关上该编号的新内存段。咱们能够以参数的方式通报一个编号,供结构函数关上现有的内存段,或许创立一个具备特定 ID 的内存段,以下

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

神秘的办法 __destructor 担任正在该内存段上挪用 shmop_close 来勾销设置工具,以与该内存段别离。咱们将这称为 “SimpleSHM 101”。如今让咱们将此办法用于更初级的用处:应用同享内存作为存储。存储数据集需求序列化,由于数组或工具无奈存储正在内存中。虽然这里应用了 JSON 来序列化,但任何其余办法(比方 XML 或内置的 PHP 序列化性能)也已足够。以下

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

咱们胜利地将一个数组序列化为一个 JSON 字符串,将它存储正在同享内存块中,从中读取数据,去序列化 JSON 字符串,并显示存储的数组。这看起来很简略,但请设想一下这个代码片断带来的可能性。您能够应用它存储 Web 效劳申请、数据库查问或许乃至模板引擎缓存的后果。正在内存中读取以及写入将带来比正在磁盘中读取以及写入更高的功能。

应用此存储技巧不只对缓存有用,也对使用顺序之间的数据替换也有用,只需数据以两端均可读的格局存储。没有要低估同享内存正在 Web 使用顺序中的力气。可采纳许多没有同的形式来巧妙地完成这类存储,唯一的限度是开发职员的发明力以及技艺。

以上就是php操作同享内存shmop类及简略应用测试(代码)的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学

抱歉,评论功能暂时关闭!