Skip to content

Instantly share code, notes, and snippets.

@fly2xiang
Created April 6, 2017 06:11
Show Gist options
  • Save fly2xiang/c35163858d074342d8d97dc17e9f0830 to your computer and use it in GitHub Desktop.
Save fly2xiang/c35163858d074342d8d97dc17e9f0830 to your computer and use it in GitHub Desktop.
PHP StreamWrapper Redis
<?php
class RedisStreamWrapper {
public $redis;
public $key;
public $position = 0;
public function __construct()
{
$this->redis = new Redis();
echo __CLASS__.__FUNCTION__.PHP_EOL;
}
public function stream_open($path, $mode, $options, &$opened_path)
{
$url = parse_url($path);
$this->redis->connect($url['host'], $url['port']);
$this->key = $url['path'];
return true;
}
public function stream_read($count)
{
$result = $this->redis->getRange($this->key, $this->position, $count);
$this->position += $count;
return $result;
}
public function stream_write($data)
{
$len = strlen($data);
$this->redis->setRange($this->key, $this->position, $data);
$this->position += $len;
return $len;
}
public function stream_tell()
{
return $this->position;
}
public function stream_eof()
{
return $this->redis->strlen($this->key) <= $this->position;
}
public function stream_seek($offset, $whence = SEEK_SET)
{
var_dump(__FUNCTION__, $offset, $whence);
switch ($whence) {
case SEEK_SET:
$this->position = $offset;
return true;
break;
case SEEK_CUR:
$this->position += $offset;
return true;
break;
case SEEK_END:
$len = $this->redis->strlen($this->key);
$this->position = $len + $offset;
return true;
break;
default:
return false;
}
}
public function stream_stat()
{
return array();
}
public function stream_close()
{
$this->redis->close();
$this->position = 0;
}
}
stream_wrapper_register('red', 'RedisStreamWrapper');
$file = 'red://127.0.0.1:6379/redis-stream-key-file';
file_put_contents($file, 'this is content');
echo file_get_contents($file).PHP_EOL;
$fd = fopen($file, 'r');
echo fread($fd, 4).PHP_EOL;
echo fread($fd, 4).PHP_EOL;
echo fread($fd, 4).PHP_EOL;
fwrite($fd, 'APPENDCONTENT');
echo file_get_contents($file).PHP_EOL;
rewind($fd);
fwrite($fd, 'line 1'.PHP_EOL);
fwrite($fd, 'line 2'.PHP_EOL);
fwrite($fd, 'line 3'.PHP_EOL);
fwrite($fd, 'line 4'.PHP_EOL);
while (!feof($fd)) {
echo fgets($fd);
}
fclose($fd);
echo file_get_contents($file).PHP_EOL;
var_dump($fd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment