php-ipc/src/Shm/SharedMemory.php

94 lines
1.7 KiB
PHP

<?php
namespace NoccyLabs\Ipc\Shm;
use NoccyLabs\Ipc\Key\KeyInterface;
/**
* Shared memory segment
*/
class SharedMemory implements \ArrayAccess
{
protected $resource;
/**
* Constructor
*
* @param KeyInterface $key
* @param integer $memsize
* @param integer $perm
*/
public function __construct(KeyInterface $key, int $memsize = 64000, int $perm = 0666)
{
if (!($shm_resource = shm_attach($key->getKey(), $memsize, $perm))) {
throw new \RuntimeException("Unable to attach shm resource {$key}");
}
$this->resource = $shm_resource;
}
/**
* Destructor
*/
public function __destruct()
{
shm_detach($this->resource);
}
/**
* Destroy the shm segment
*
* @return void
*/
public function destroy()
{
shm_remove($this->resource);
}
/**
* {@inheritDoc}
*
* @param int $offset
* @return void
*/
public function offsetExists($offset)
{
return shm_has_var($this->resource, $offset);
}
/**
* {@inheritDoc}
*
* @param int $offset
* @return mixed
*/
public function offsetGet($offset)
{
return shm_has_var($this->resource, $offset)?shm_get_var($this->resource, $offset):null;
}
/**
* {@inheritDoc}
*
* @param int $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value)
{
shm_put_var($this->resource, $offset, $value);
}
/**
* {@inheritDoc}
*
* @param int $offset
* @return void
*/
public function offsetUnset($offset)
{
shm_remove_var($this->resource, $offset);
}
}