PHP Stream Wrapper

原文:http://blog.sina.com.cn/s/blog_502c8cc40100k40e.html ,主要是基于SAE环境讲述相应的应用场景,本文经过一定的整理和少量补充。

一、PHP Wrapper是什么

自PHP 4.3开始,PHP开始允许用户通过stream_wrapper_register()自定义URL风格的协议。用户使用fopen(), copy()等文件系统函数对封装协议进行操作时,PHP会调用注册协议时所提供的类中相应的函数。

PHP手册中给了一个例子,它将VariableStream类注册为var://协议,通过这个协议,用户可以使用文件系统函数直接读写全局变量。例如,用户可以通过 “var://foo” 存取 $GLOBALS['foo']

二、为什么需要PHP Wrapper

以SAE为例。

出于性能和安全方面的考虑,SAE平台上禁用了本地文件读写和对外的数据抓取。相应的,我们提供了对应的服务来做同样的事情。

由于新服务的接口和PHP本身的接口不太一样,专门为SAE平台开发的程序当然不会存在问题,但是大量已有的程序和开源项目,就面临着繁杂的迁移工作。而使用PHP Wrapper对SAE的服务进行封装之后,用户就可以更方便地将程序迁移到SAE平台。

三、如何写PHP Wrapper

要通过PHP Wrapper封装一个协议,首先,我们需要编写 streamWrapper 类,类名可自定义,类的格式为:

streamWrapper {

    public resource $context ;

    __construct ( void )
public bool dir_closedir ( void )
public bool dir_opendir ( string $path , int $options )
public string dir_readdir ( void )
public bool dir_rewinddir ( void )
public bool mkdir ( string $path , int $mode , int $options )
public bool rename ( string $path_from , string $path_to )
public bool rmdir ( string $path , int $options )
public resource stream_cast ( int $cast_as )
public void stream_close ( void )
public bool stream_eof ( void )
public bool stream_flush ( void )
public bool stream_lock ( mode $operation )
public bool stream_open ( string $path , string $mode , int $options , string &$opened_path )
public string stream_read ( int $count )
public bool stream_seek ( int $offset , int $whence = SEEK_SET )
public bool stream_set_option ( int $option , int $arg1 , int $arg2 )
public array stream_stat ( void )
public int stream_tell ( void )
public int stream_write ( string $data )
public function stream_metadata($path, $option, $value)
public function stream_set_option($option, $arg1, $arg2)
public function stream_truncate($new_size)
public bool unlink ( string $path )
public array url_stat ( string $path , int $flags )
}

类中各方法说明:

  • streamWrapper::__construct — 构造函数,仅在stream_open前被调用
  • streamWrapper::dir_closedir — 关闭目录句柄,响应closedir()函数
  • streamWrapper::dir_opendir — 打开目录句柄,响应opendir()函数
  • streamWrapper::dir_readdir — 从目录句柄读取条目,响应readdir()函数
  • streamWrapper::dir_rewinddir — 倒回目录句柄,响应rewinddir()函数
  • streamWrapper::mkdir — 创建目录,响应mkdir()函数
  • streamWrapper::rename — 目录或文件重命名,响应rename()函数
  • streamWrapper::rmdir — 删除目录,响应rmdir()函数
  • streamWrapper::stream_cast — 检索基础资源,响应stream_select()函数
  • streamWrapper::stream_close — 关闭资源,响应fclose()函数
  • streamWrapper::stream_eof — 检查文件指针是否已经在文件末尾,响应feof()函数
  • streamWrapper::stream_flush — 清除输出缓存,响应fflush()函数
  • streamWrapper::stream_lock — 咨询文件锁定,响应flock()函数
  • streamWrapper::stream_open — 打开文件或URL为流,响应fopen()函数
  • streamWrapper::stream_read — 从流中读取内容,响应fread(), fgets()函数
  • streamWrapper::stream_seek — 在流中定位指针,响应fseek()函数
  • streamWrapper::stream_set_option — 改变流设置
  • streamWrapper::stream_stat — 检索文件资源的信息,响应fstat()函数
  • streamWrapper::stream_tell — 检索流中指针的位置,响应ftell()函数
  • streamWrapper::stream_write — 向流中写入内容,响应fwrite(), fputs()函数
  • streamWrapper::unlink — 删除文件,响应unlink()函数
  • streamWrapper::url_stat — 检索文件的信息,响应所有stat()相关的函数,例如file_exists(), is_dir(), is_file(), filesize(), fileinode()等等

详细说明请参考PHP手册:http://cn2.php.net/manual/en/class.streamwrapper.php

写好streamWrapper类之后,使用 stream_wrapper_register() 将这个类注册到Wrapper中,就可以开始使用了。

函数使用方法为:

bool stream_wrapper_register ( string $protocol , string $classname [, int $flags = 0 ] )

例如:

stream_wrapper_register("saemc", "SaeMemcacheWrapper");

由于SAE平台不支持对本地文件的写操作,因此Smarty之类的一些需要在本地写文件的开源项目就没办法直接在SAE平台上使用,而有了saemc Wrapper,用户就可以将Smarty编译的模板保存在MC中,很方便的将Smarty迁移到SAE平台上来。

在附件中我们为大家提供了SAE上Memcache Wrapper的实现代码,大家可以下载此附件进行测试。

在测试之前,需要先在本地启动一个端口为22222的Memcached服务:

memcached -m 10 -p 22222 -u nobody -l 127.0.0.1

然后使用下面代码就可以测试了:

//包含附件代码,注册saemc Wrapper
include_once('wrapper.php');
//测试 saemc Wrapper
$fp = fopen( "saemc://test.txt", "w+" ) or die("fopen faild!");
fwrite( $fp, "line1\n" ) or die("fwrite line1 faild!");
fwrite( $fp, "line2\n" ) or die("fwrite line2 faild!");
fwrite( $fp, "line3\n" ) or die("fwrite line3 faild!");
var_dump(ftell($fp));
fseek( $fp, 0 );
while ( !feof( $fp ) ) {
$c = fgets( $fp ) or die("fgets faild!");
var_dump($c);
}
fclose( $fp );
var_dump(file_get_contents("saemc://test.txt"));
var_dump(file_put_contents("saemc://path/test.txt", "hello world!\n"));
var_dump(file_put_contents("saemc://path/test.txt", "hello world!\n", FILE_APPEND));
var_dump(file_get_contents("saemc://path/test.txt"));
var_dump(copy("saemc://path/test.txt", "saemc://path/test_new.txt"));
var_dump(file_get_contents("saemc://path/test_new.txt"));
var_dump(unlink("saemc://path/test.txt"));
var_dump(file_get_contents("saemc://path/test.txt"));
var_dump(rename("saemc://path/test_new.txt", "saemc://path/test.txt"));
var_dump(file_get_contents("saemc://path/test.txt"));
echo "====test include====\n";
include_once("saemc://path/test.txt");

测试页面的输出结果:

int(18)
string(6) "line1
"
string(6) "line2
"
string(6) "line3
"
string(18) "line1
line2
line3
"
int(13)
int(13)
string(26) "hello world!
hello world!
"
bool(true)
string(26) "hello world!
hello world!
"
bool(true)
bool(false)
bool(true)
string(26) "hello world!
hello world!
"
====test include====
hello world!
hello world!

我们提供的 Memcache Wrapper并没有实现目录操作的一些方法和Memcache的Timeout,大家可以参考PHP手册,尝试实现目录操作,或者通过context使这个Wrapper支持Memcache的Timeout。

另外,大家可以到下面这个地址查看SAE Stdlib中sae_include的源码,在其中还有我们为Storage服务封装的saestor Wrapper和为Fetchurl服务重新封装的http Wrapper的实现:

http://stdlib.sinaapp.com/?f=sae_include.function.php

四、写Wrapper时的一些注意事项

1、 构造函数

streamWrapper 类很特别,它的构造函数并不是每次都调用的。只有在你的操作触发了stream_open相关的操作时才会调用,比如你用 file_get_contents() 了。而当你的操作触发和stream无关的函数时,比如file_exists会触发url_stat方法,这个时候构造函数是不会被调用的。

2、 读实现

Wrapper里边有Position和Seek等概念,但是很多服务其实是一次性就读取全部数据的,这个可以在stream_open的时候一次性读回,放到一个属性中,以后seek和tell的时候直接操作属性里边存放的数据就可以了。

3、 追加写实现

有很多服务是一次性写入所有数据,不支持追加写的功能(比如Memcache),这就需要我们自己在Wrapper中来实现追加写。可以将整个value一次性读取出来,将需要追加写的数据追加在读取出来的内容后面之后,再一次性写回。

但是这种追加写的实现方式性能会比较差,尤其是内容体积较大之后,一次性读取所有内容会非常消耗资源,因此在某些服务中我们不得不舍弃对追加写的支持。

4、 url_stat的实现

在streamWrapper类的实现中,url_stat的实现是个难点。必须正确的实现url_stat才能使is_writable和is_readable等查询文件元信息的函数正常工作。

而我们需要为我们的虚设备伪造这些值。以mc为例,我们给大家一些参考数据:

url_stat应该返回一个数组,分13个项,内容如下:

字段名 说明 赋值
dev 设备号 写0即可
ino inode号 写0即可
mode 文件mode 这个是文件的权限控制符号,稍后详细说明
nlink link 写0即可
uid uid Linux上用posix_get_uid可以取到,windows上为0
gid gid Linux上用posix_get_gid可以取到,windows上为0
rdev 设备类型 当为inode设备时有值
size 文件大小
atime 最后读时间 格式为unix时间戳
mtime 最后写时间
ctime 创建时间
blksize blocksize of filesystem IO 写0即可
blocks number of 512-byte blocks allocated 写0即可

其中mode的值必须写对:

如果是文件,其值为:

0100000 + 文件权限,如 0100000 + 0777

如果是目录,其值为:

040000 + 目录权限,如 0400000 + 0777

5、 关于stat的缓存

PHP会在同一个页面的执行过程中对文件的元信息进行缓存。

根据PHP文档对 clearstatcache() 这个方法的说明得知:在使用 stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), 或 fileperms() 方法查询文件信息时,PHP会将文件的stat的缓存以提高性能。 clearstatcache()方法可以用来清除这个缓存,当unlink()会自动清除stat缓存。

而实际上,PHP只有在对本地文件进行unlink, rename和rmdir操作时会清除stat缓存,而在通过其他的wrapper进行unlink, rename和rmdir操作时,并不会清除stat缓存。因此在写wrapper时我们要自己在unlink等方法中通过clearstatcache()来清除stat缓存。

附件下载地址: http://apidoc-demo.stor.sinaapp.com/wrapper.php

[转] 基于PHP Stream Wrapper开发有趣应用场景的更多相关文章

  1. 基于Vivado的嵌入式开发 ——PS+PL实践

    基于Vivado的嵌入式开发 ——PS走起 硬件平台:ZedBoard 开发工具:Vivado 2014.2 1.规划 废话不多说,依然是流水灯,这次是采用PS+PL实现. 功能依旧简单,目标是为了学 ...

  2. 基于 SailingEase WinForm Framework 开发优秀的客户端应用程序(目录)

    本系统文章将详细阐述客户端应用程序的设计理念,实现方法. 本系列文章以  SailingEase WinForm Framework 为基础进行设计并实现,但其中的设计理念及方法,亦适用于任何类型的客 ...

  3. [转]基于Starling移动项目开发准备工作

    最近自己趁业余时间做的flash小游戏已经开发得差不多了,准备再完善下ui及数值后,投放到国外flash游戏站.期间也萌生想法,想把游戏拓展到手机平台.这两天尝试了下,除去要接入ane接口的工作,小游 ...

  4. 最新基于adt-bundle-windows-x86的android开发环境筹建

    最新基于adt-bundle-windows-x86的android开发环境搭建 某系统要配套做一个android客户端,来一次android开发环境快速搭建,系统Win7,具体步骤如下: 1.下载j ...

  5. 基于Typecho CMS框架开发大中型应用

    基于Typecho CMS框架开发大中型应用 大中型应用暂且定义为:大于等于3个数据表的应用!汗吧! Typecho原本是一款博客系统,其框架体系有别于市面上一般意义MVC框架,主体代码以自创的Wid ...

  6. Android基于XMPP Smack openfire 开发的聊天室

    Android基于XMPP Smack openfire 开发的聊天室(一)[会议服务.聊天室列表.加入] http://blog.csdn.net/lnb333666/article/details ...

  7. 基于Android 4.4 开发的多窗体系统 开放源代码

    Hi, 这是我基于Android 4.4开发的多窗体系统,还有非常多不足,还请多多不吝赐教啊,代码已经所有开源. 视频地址 源代码地址 Done: 1. APP以窗体化显示 在 PhoneWindow ...

  8. 基于MINA框架快速开发网络应用程序

    1.MINA框架简介 MINA(Multipurpose Infrastructure for Network Applications)是用于开发高性能和高可用性的网络应用程序的基础框架.通过使用M ...

  9. Spring 基于注解零配置开发

    本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址:< Spring 基于注解零配置开发 > 一:搜索Bean 再也不用在XML文件里写什么配置信息了. Sprin ...

随机推荐

  1. 64位Windows下安装Redis教程

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/104.html?1455868495 Redis对于Linux​是官方支持 ...

  2. 基础才是重中之重~LazyInitializer.EnsureInitialized对属性实现化的性能优化

    回到目录 LazyInitializer.EnsureInitialized是frameworks4.0引入的新东西,实现对属性延时初始化的功能,它作用在System.Threading命名空间下,所 ...

  3. Change Git Default Editor in Windows

    On 32 bit Win OS: git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' - ...

  4. 重构Mybatis与Spring集成的SqlSessionFactoryBean(2)

    三.代码重构 1.先使用Eclipse把buildSqlSessionFactory()方法中众多的if换成小函数 protected SqlSessionFactory buildSqlSessio ...

  5. poj 2195 Going Home

    /* 做网络流的题建图真的是太重要了! 本题是将人所在的位置和房子所在的位置建立边的联系,其中man到house这一条边的流量为 1, 费用为两者的距离 而方向边的流量为 0, 费用为正向边的相反数( ...

  6. POJ 2312Battle City(BFS-priority_queue 或者是建图spfa)

    /* bfs搜索!要注意的是点与点的权值是不一样的哦! 空地到空地的步数是1, 空地到墙的步数是2(轰一炮+移过去) 所以用到优先队列进行对当前节点步数的更新! */ #include<iost ...

  7. MYSQL线程池总结(一)

    线程池是Mysql5.6的一个核心功能,对于服务器应用而言,无论是web应用服务还是DB服务,高并发请求始终是一个绕不开的话题.当有大量请求并发访问时,一定伴随着资源的不断创建和释放,导致资源利用率低 ...

  8. C#调用Couchbase中的Memcached缓存

    安装服务端 服务端下载地址:http://www.couchbase.com/download 选择适合自己的进行下载安装就可以了,我这里选择的是Win7 64. 服务端安装完后,如果成功了,那么在浏 ...

  9. Testing - 测试基础 - 自动

    自动化测试模型 一个自动化测试框架就是一个集成体系,在这一体系中包含测试功能的函数库.测试数据源.测试对象识别标准,以及种可重用的模块. 自动化测试框架在发展的过程中,不断有新的模型(概念)被提出,目 ...

  10. 探秘Tomcat(一)——Myeclipse中导入Tomcat源码

    前言:有的时候自己不知道自己是井底之蛙,这并没有什么可怕的,因为你只要蜷缩在方寸之间的井里,无数次的生活轨迹无非最终归结还是一个圆形:但是可怕的是有一天你不得不从井里跳出来生活,需要重新审视井以外的生 ...