Ejemplo de clase registrada como envoltura de flujo

El ejemplo de abajo implementa un gestor de protocolo var:// que permite el acceso a la lectura/escritura de una variable global nominada usando un flujo de sistema de archivos estándar tal como fread(). El protocolo var:// implementado abajo, dada la URL "var://foo", leerá/escribirá información hacia/desde $GLOBALS["foo"].

Ejemplo #1 Un Flujo para leer/escribir variables globales

<?php

class FlujoVariable {
var
$posición;
var
$nombre;

function
stream_open($ruta, $modo, $opciones, &$ruta_abierta)
{
$url = parse_url($ruta);
$this->nombre = $url["host"];
$this->posición = 0;

return
true;
}

function
stream_read($cuenta)
{
$ret = substr($GLOBALS[$this->nombre], $this->posición, $cuenta);
$this->posición += strlen($ret);
return
$ret;
}

function
stream_write($data)
{
$izquierda = substr($GLOBALS[$this->nombre], 0, $this->posición);
$derecha = substr($GLOBALS[$this->nombre], $this->posición + strlen($data));
$GLOBALS[$this->nombre] = $izquierda . $data . $derecha;
$this->posición += strlen($data);
return
strlen($data);
}

function
stream_tell()
{
return
$this->posición;
}

function
stream_eof()
{
return
$this->posición >= strlen($GLOBALS[$this->nombre]);
}

function
stream_seek($índice, $dónde)
{
switch (
$dónde) {
case
SEEK_SET:
if (
$índice < strlen($GLOBALS[$this->nombre]) && $índice >= 0) {
$this->posición = $índice;
return
true;
} else {
return
false;
}
break;

case
SEEK_CUR:
if (
$índice >= 0) {
$this->posición += $índice;
return
true;
} else {
return
false;
}
break;

case
SEEK_END:
if (
strlen($GLOBALS[$this->nombre]) + $índice >= 0) {
$this->posición = strlen($GLOBALS[$this->nombre]) + $índice;
return
true;
} else {
return
false;
}
break;

default:
return
false;
}
}

function
stream_metadata($ruta, $opción, $var)
{
if(
$opción== STREAM_META_TOUCH) {
$url = parse_url($ruta);
$varname = $url["host"];
if(!isset(
$GLOBALS[$varname])) {
$GLOBALS[$varname] = '';
}
return
true;
}
return
false;
}
}

stream_wrapper_register("var", "FlujoVariable")
or die(
"Error al registrar el protocolo");

$mivar = "";

$fp = fopen("var://mivar", "r+");

fwrite($fp, "línea1\n");
fwrite($fp, "línea2\n");
fwrite($fp, "línea3\n");

rewind($fp);
while (!
feof($fp)) {
echo
fgets($fp);
}
fclose($fp);
var_dump($mivar);

?>

El resultado del ejemplo sería:

 línea1 línea2 línea3 string(24) "línea1 línea2 línea3 " 
To Top