php router 类有什么好处

盘点四个非常实用的PHP功能 _ 路由器设置|192.168.1.1|无线路由器设置|192.168.0.1 - 路饭网
您的位置: >
> 阅读资讯:盘点四个非常实用的PHP功能
盘点四个非常实用的PHP功能
盘点四个非常实用的PHP功能
最近写的几个PHP实用功能整理了一下,弄成一个文档,写上说明,方便以后使用!一共有4个PHP实用功能,现在跟大家分享,喜欢的朋友可以把它收藏起来,说不定以后用得上。
1. PHP函数的任意数目的参数
您可能知道PHP允许你定义一个默认参数的函数。但您可能并不知道PHP还允许你定义一个完全任意的参数的函数
下面是一个示例向你展示了默认参数的函数:
// 两个默认参数的函数
function foo($arg1 = '', $arg2 = '') {
echo &arg1: $arg1\n&;
echo &arg2: $arg2\n&;
foo('hello','world');
arg1: hello
arg2: world
现在我们来看一看一个不定参数的函数,其使用到了func_get_args()方法:
// 是的,形参列表为空
function foo() {
// 取得所有的传入参数的数组
$args = func_get_args();
foreach ($args as $k =& $v) {
echo &arg&.($k+1).&: $v\n&;
/* 什么也不会输出 */
foo('hello');
arg1: hello
foo('hello', 'world', 'again');
arg1: hello
arg2: world
arg3: again
2. Glob() 查找文件
有很多PHP的函数都有一个比较长的自解释的函数名,但是,当您看到glob() 的时候,您可能并不知道这个函数是用来干什么的,除非您对它已经很熟悉了。
你可以认为这个函数就好?scandir() 一样,其可以用来查找文件。
// 取得所有的后缀为PHP的文件
$files = glob('*.php');
print_r($files);
[0] =& phptest.php
[1] =& pi.php
[2] =& post_output.php
[3] =& test.php
您还可以查找多种后缀名
// 取PHP文件和TXT文件
$files = glob('*.{php,txt}', GLOB_BRACE);
print_r($files);
[0] =& phptest.php
[1] =& pi.php
[2] =& post_output.php
[3] =& test.php
[4] =& log.txt
[5] =& test.txt
您还可以加上路径:
$files = glob('../images/a*.jpg');
print_r($files);
[0] =& ../images/apple.jpg
[1] =& ../images/art.jpg
如果你想得到绝对路径,你可以调用?realpath() 函数:
$files = glob('../images/a*.jpg');
// applies the function to each array element
$files = array_map('realpath',$files);
print_r($files);
/* output looks like:
[0] =& C:\wamp\www\images\apple.jpg
[1] =& C:\wamp\www\images\art.jpg
3. 查看内存使用情况
观察你程序的内存使用能够让你更好的优化你的代码。
PHP 是有垃圾回收机制的,而且有一套很复杂的内存管理机制。你可以知道你的脚本所使用的内存情况。要知道当前内存使用情况,你可以使用?memory_get_usage() 函数,如果你想知道使用内存的峰值,你可以调用memory_get_peak_usage() 函数。
echo &Initial: &.memory_get_usage().& bytes \n&;
Initial: 361400 bytes
// 使用内存
for ($i = 0; $i & 100000; $i++) {
$array []= md5($i);
// 删除一半的内存
for ($i = 0; $i & 100000; $i++) {
unset($array[$i]);
echo &Final: &.memory_get_usage().& bytes \n&;
Final: 885912 bytes
echo &Peak: &.memory_get_peak_usage().& bytes \n&;
/* 输出峰值
4. 查看CPU使用情况
使用?getrusage() 函数可以让你知道CPU的使用情况。注意,这个功能在Windows下不可用。
print_r(getrusage());
[ru_oublock] =& 0
[ru_inblock] =& 0
[ru_msgsnd] =& 2
[ru_msgrcv] =& 3
[ru_maxrss] =& 12692
[ru_ixrss] =& 764
[ru_idrss] =& 3864
[ru_minflt] =& 94
[ru_majflt] =& 0
[ru_nsignals] =& 1
[ru_nvcsw] =& 67
[ru_nivcsw] =& 4
[ru_nswap] =& 0
[ru_utime.tv_usec] =& 0
[ru_utime.tv_sec] =& 0
[ru_stime.tv_usec] =& 6269
[ru_stime.tv_sec] =& 0
这个结构看上出很晦涩,除非你对CPU很了解。下面一些解释:
ru_oublock: 块输出操作
ru_inblock: 块输入操作
ru_msgsnd: 发送的message
ru_msgrcv: 收到的message
ru_maxrss: 最大驻留集大小
ru_ixrss: 全部共享内存大小
ru_idrss:全部非共享内存大小
ru_minflt: 页回收
ru_majflt: 页失效
ru_nsignals: 收到的信号
ru_nvcsw: 主动上下文切换
ru_nivcsw: 被动上下文切换
ru_nswap: 交换区
ru_utime.tv_usec: 用户态时间 (microseconds)
ru_utime.tv_sec: 用户态时间(seconds)
ru_stime.tv_usec: 系统内核时间 (microseconds)
ru_stime.tv_sec: 系统内核时间?(seconds)
以上就是分享给大家的PHP实用功能,希望对大家的学习有所帮助。
本文地址:
相关文章列表php怎么使用广告路由接口协议做wifi管理系统?
php怎么使用广告路由接口协议做wifi管理系统
这个具体可以参考wifidog他们是基于dd-wrt的wifi的web端管理方案,建议你可以整合下微信的接口进行研究;
已有帐号?
无法登录?
社交帐号登录安全检查中...
请打开游览器的javascript,然后刷新游览器
浏览器安全检查中… .
还剩 5 秒&php框架内一般都是单入口请求,比如
$front = Front::getInstance();
$front-&run();
在run()方法里面将对请求进行处理
class IF_FrontController{
protected $request =
protected $router =
protected $dispatcher =
//请求对象
public function getRequest() {
if(!$this-&request) {
$this-&request = new IF_Request();
return $this-&
public function getRouter() {
if(!$this-&router) {
$this-&router = new IF_Router();
return $this-&
public function getDispatcher() {
if(!$this-&dispatcher) {
$this-&dispatcher = new IF_Dispatcher();
return $this-&
public function run($request = null) {
if($request == null) {
$request = $this-&getRequest();
if(!$request-&routed) {
$request-&routed =
$this-&getRouter()-&route($request);
$dispatcher = $this-&getDispatcher();
$dispatcher-&dispatcher($request);
第一步,即生成一个request对象,对$_SERVER['REQUEST_URI']分析处理,生成几个request属性,如$request-&url。
class IF_Request{
public $baseurl = '/xxx';
public $controller = 'index';
public $action = 'index';
public $routed =
public $dispatcher =
public function __construct($init = true) {
if($init == false) return '';
//这块解析稍微有点乱
if($_SERVER['HTTP_HOST'] == 'localhost') {
if(false !== strpos($_SERVER['REQUEST_URI'],'.php')) {
$this-&url = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'],'.php')+4);
$this-&url = substr($_SERVER['REQUEST_URI'], strlen($this-&baseurl));
$this-&url = $_SERVER['REQUEST_URI'];
第二步,将request对象抛给路由解析对象。按照业务的逻辑或者路由规则解析request-&url,生成其他的几个request属性,比如$request-&controller,$request-&action。
class IF_Router{
public function route($request) {
$this-&explain($request);
public function explain($request) {
if(!$request-&url) return '';
$segments = explode('/', trim(array_shift(explode('?', $request-&url)), '/'));
if(!empty($segments[0])){
$request-&controller = $segments[0];
if(isset($segments[1])){
$request-&action = $segments[1];
第三步,初始化调度器对象,然后将$request对象抛给调度器,调度器这里可以初始化一些全局的类,如Config类等。然后解析request,最终实现
class IF_Dispatcher{
public function dispatcher($request){
load_class('Config', 'core');
list($classname, $method) = $this-&loadAction($request);
if(!class_exists($classname)) {
header('HTTP/1.1 404 Not Found');;
echo '&h1&404!&/h1&';
return '';
$instance = new $classname();
if(!method_exists($instance, $method)){
header('HTTP/1.1 404 Not Found');;
echo '&h1&404!&/h1&';
return '';
$instance-&$method();
public function loadAction($request) {
$controller = $request-&
$action = $request-&
$classname = ucfirst($controller).'Controller';
$method = &{$action}Action&;
$controllerBasePath = APP_PATH.'/controller';
$controllerFileName = $controllerBasePath.'/'.$classname.'.php';
if (file_exists($controllerFileName)) {
require_once $controllerFileN
return array($classname, $method);
也可以在解析过程中,对非法的请求方式进行友好的错误提示等等等。
在PHP的论坛中总是听到有人对PHP的OOP支持说三道四的,说这有缺陷,那里不足,但是都拿不出实际的例子。原来说过要和大家说说这事,但是一直很忙,现在算是抽了些时间了,所以把我刚刚做过的一个项目的框架拿出来和大家探讨一下。这个项目99%的代码是用oop方式编写的,感觉PHP对于OOP支持非常好,不是一般的好,是非常的好。有由于项目本身是一个商业项目所以源代码不好公布出来,但是基本框架还是可以说一说的,而且经过简化的例子更容易理解一些。如果你对PHP中的OOP还不太了解,还是就此打住吧,先去看看手册,或者基础读物再来看也不迟,反正这个是贴子没有长腿也跑不了。
长话短说,立刻开始吧。我这里会用到一个简单的例子,只有一个半的功能。一个是向浏览器发送一句”Hello, I can say OOP in PHP world!”,另外半个功能是从数据库中进行一个查询然后输出到浏览器,说它是半个功能是因为只是作为一个例子讲讲没有实际的数据库操作。
首先从我的第一个文件index.php 开始介绍吧。我的index.php文件是这样的:
include_once ('config.php');
include_once ('class.Application.php');
$app = & new Application();
$app-&run();
这个就是全部了,虽然只有4行,但是如果用OOP的方式写这个应该就够了吧。 有一点经验的哥们会发现这里只用到了一个Application 对象,那么一定很想知道这个对象究竟长什么样呢?我们继续看看class.Application.php 这个文件的内部。从以上的代码中我们知道她应该至少包含两个方法 Application() 和 run() 所以大体上应该长成这样
class Application
function Application()
function run()
现在就算知道Application 是什么样,它好像也没有办法完成我们预先设定的功能呀? 所以还要介绍一下如何运行这个程序,在我的结构中所有的页面都是通过index.php和一个action参数进行访问的例如第一个功能应该这样访问index.php?action=HelloPage,而第二个功能则是通过index.php?action=DatabasePage进行访问。这样的结构大家也许并不陌生吧。所以index.php 页面应当知道传进来的 action 参数是什么,也就是说Application对象应当知道 这个action 参数是什么。所以我们需要给Application增加一个方法 getAction()来获得action参数。既然知道action,知道了要做什么,那么方法 run()也就有知道如何去run了。
同时我还可以把(完成功能的)每一个页面作为一个对象来看待,所以我应该至少还需要两个类
class HelloPage 和
class DatabasePage
由于这两个对象最终都是向浏览器发送页面所以把他们共同的部分提出来作为他们的父类
class Page
以下是三个类文件的内容
class.Page.php
class Page
function Page()
function show()
//不能直接调用这个方法一定要在子类中去具体实现。
die('You can not use this funciton directly from Page class');
其中这个show方法应该是所有页面对象都具有的方法,只是在实现上有所不同。
class.HelloPage.php
require_once (&class.Page.php&);
class HelloPage extends Page
function HelloPage()
parent::Page();
function show()
echo &Hello, I can say OOP in PHP world!&;
class.DatabasePage.php
require_once (&class.Page.php&);
class DatabasePage extends Page
function DatabasePage()
parent::Page();
function show()
//做一些数据库操作然后将结果显示出来。
同时我们还遵守这样的一条规则:action的值和调用的页面类的名称保持一致,例如当action=HelloPage的时候程序就知道需要初始化一个HelloPage的对象,有了这样的规则和以上的几个文件我们就可以将 Application 类改进成这样。
class Application
function Application()
function getAction()
function run()
$pageClass = $this-&getAction();
include_once (&class.&.$pageClass.&.php&);
$page = & new $pageClass();
$page-&show();
为什么getAction()空着?因为它太简单了,你自己可以轻松地把它写出来呀。
看到这里,如果你还不太明白,不用急,可以停下来重新再看一遍。
如果全明白了,我们就继续前进。我们还有半个任务没有完成,所以我们需要改进我们的Application和页面类,让它完成数据库操作功能。
进行数据库操作之前首先应当得到一个正确的数据库连接,如果让每个需要数据库连接的页面类去做这样的工作实在是一件非常费时费力的工作,不容易维护管理而且也破坏了oop的设计初衷,进行数据库操作的页面类例如 DatabasePage 只应当完成它份内工作即获得数据。 仔细看看我们的设计不难发现建立数据库连接的工作交给 Application 来做最合适不过了, 所以给Application 增加一个新的成员 $db 并且在初始化的时候将建立的数据库连接赋值给它。
require_once (&class.Database.php&);
class Application
var $//数据库对象
function Application()
//$db 现在是一个数据库对象了
$this-&db = & new Database(DB_HOST,DB_NAME,DB_LOGIN,DB_PASS);
function getAction()
return $_GET['action']; //简单的实现 getA
funciton & getDatabase()
return $this-&
function run()
$pageClass = $this-&getAction();
include_once (&class.&.$pageClass.&.php&);
$page = & new $pageClass($this);
//这里是唯一做了手脚的地方,将这个Application对象传给页面对象。
$page-&show();
你现在不用太关心这个 Database对象从何而来如何实现,知道它是一个含有数据库连接的对象就可以了,如果用过phplib, ADODB,或者Pear库的就很容易理解。 这个语句: $this-&db = & new Database(DB_HOST,DB_NAME,DB_LOGIN,DB_PASS); 就是建立一个数据库连接而已。
至于DB_HOST,DB_NAME,DB_LOGIN,DB_PASS 这些都是常量我们在config.php中已经预先设定。
由于数据库操作页面 DatabasePage 需要进行数据库连接所以它也需要一个变量 $db 来保存数据库对象,所以我们需要把DatabasePage改进成这样:
class.DatabasePage.php
require_once (&class.Page.php&);
class DatabasePage extends Page
//将Application对象作为参数接受。
function DatabasePage(&$app)
parent::Page();
//获得 Application 中的数据库对象。
$this-&db = $app-&getDatabase();
function show()
//简单的一个 SQL 例子。
$sql = 'SELECT * FROM sale_orders';
//query 是 Database对象的一个公共的方法,通过它向数据库提交SQL查询。
$results = $this-&;db-&;query($sql);
好了,一个半的功能算是完成了,PHP对于OOP支持得也很漂亮吧,结构清晰,维护方便,至于效率嘛,我可没看出来有什么损失,如果你有兴趣可以自己测试一下。用这样的框架可以轻松应对各种需求的变化:增加各种权限控制,分离数据库层,商业逻辑,和表象层,增加远程调用接口统统不成问题,只是这里实在写不完这么多的东西。真不知道谁还会有理由说PHP 中OOP 很烂呢?
另外,需要提醒大家的是传递对象和赋值的时候要使用 &符号这样可以保证每次引用的是同一个对象。
转载:http://bbs.chinaunix.net/thread--1.html
// Change the title using array syntax
$A['title'] = ‘SPL _really_ rocks’;
// Try setting a non existent property (ignored)
$A['not found'] = 1;
// Unset the author field
unset($A['author']);
// Check what it looks like again
echo ‘Final State:
print_r($A);
echo ‘
运行结果如下:
Initial State:
Article Object
[title] => SPL Rocks
[author] => Joe Bloggs
[category] => PHP
Final State:
Article Object
[title] => SPL _really_ rocks
[category] => PHP
可以看到,$A虽然是一个object,但是完全可以像array那样操作。
你还可以在读取数据时,增加程序内部的逻辑:
function offsetGet($key) {
if ( array_key_exists($key,get_object_vars($this)) ) {
return strtolower($this->{$key});
5. IteratorAggregate界面
但是,虽然$A可以像数组那样操作,却无法使用foreach遍历,除非部署了前面提到的Iterator界面。
另一个解决方法是,有时会需要将数据和遍历部分分开,这时就可以部署IteratorAggregate界面。它规定了一个getIterator()方法,返回一个使用Iterator界面的object。
还是以上一节的Article类为例:
class Article implements ArrayAccess, IteratorAggregate {
* Defined by IteratorAggregate interface
* Returns an iterator for for this object, for use with foreach
* @return ArrayIterator
function getIterator() {
return new ArrayIterator($this);
使用方法如下:
$A = new Article(‘SPL Rocks’,'Joe Bloggs’, ‘PHP’);
// Loop (getIterator will be called automatically)
echo ‘Looping with foreach:
foreach ( $A as $field => $value ) {
echo “$field : $value“;
echo ‘
// Get the size of the iterator (see how many properties are left)
echo “Object has “.sizeof($A->getIterator()).” elements”;
显示结果如下:
Looping with foreach:
title : SPL Rocks
author : Joe Bloggs
category : PHP
Object has 3 elements
6. RecursiveIterator界面
这个界面用于遍历多层数据,它继承了Iterator界面,因而也具有标准的current()、key()、next()、 rewind()和valid()方法。同时,它自己还规定了getChildren()和hasChildren()方法。The getChildren() method must return an object that implements RecursiveIterator.
7. SeekableIterator界面
SeekableIterator界面也是Iterator界面的延伸,除了Iterator的5个方法以外,还规定了seek()方法,参数是元素的位置,返回该元素。如果该位置不存在,则抛出OutOfBoundsException。
下面是一个是实例:
class PartyMemberIterator implements SeekableIterator
public function __construct(PartyMember $member)
// Store $member locally for iteration
public function seek($index)
$this->rewind();
$position = 0;
while ($position valid()) {
$this->next();
$position++;
if (!$this->valid()) {
throw new OutOfBoundsException(‘Invalid position’);
// Implement current(), key(), next(), rewind()
// and valid() to iterate over data in $member
8. Countable界面
这个界面规定了一个count()方法,返回结果集的数量。
第三部分 SPL Classes
9. SPL的内置类
SPL除了定义一系列Interfaces以外,还提供一系列的内置类,它们对应不同的任务,大大简化了编程。
查看所有的内置类,可以使用下面的代码:
// a simple foreach() to traverse the SPL class names
foreach(spl_classes() as $key=>$value)
echo $key.’ -& ‘.$value.’‘;
10. DirectoryIterator类
这个类用来查看一个目录中的所有文件和子目录:
/*** class create new DirectoryIterator Object ***/
foreach ( new DirectoryIterator('./') as $Item )
echo $Item.'‘;
/*** if an exception is thrown, catch it here ***/
catch(Exception $e){
echo ‘No files Found!‘;
查看文件的详细信息:
foreach(new DirectoryIterator('./' ) as $file )
if( $file->getFilename()
== ‘foo.txt’ )
echo ‘
getFilename()
‘; var_dump($file->getFilename()); echo ‘
echo ‘
getBasename()
‘; var_dump($file->getBasename()); echo ‘
echo ‘
‘; var_dump($file->isDot()); echo ‘
echo ‘
__toString()
‘; var_dump($file->__toString()); echo ‘
echo ‘
‘; var_dump($file->getPath()); echo ‘
echo ‘
getPathname()
‘; var_dump($file->getPathname()); echo ‘
echo ‘
getPerms()
‘; var_dump($file->getPerms()); echo ‘
echo ‘
getInode()
‘; var_dump($file->getInode()); echo ‘
echo ‘
‘; var_dump($file->getSize()); echo ‘
echo ‘
getOwner()
‘; var_dump($file->getOwner()); echo ‘
echo ‘
$file->getGroup()
‘; var_dump($file->getGroup()); echo ‘
echo ‘
getATime()
‘; var_dump($file->getATime()); echo ‘
echo ‘
getMTime()
‘; var_dump($file->getMTime()); echo ‘
echo ‘
getCTime()
‘; var_dump($file->getCTime()); echo ‘
echo ‘
‘; var_dump($file->getType()); echo ‘
echo ‘
isWritable()
‘; var_dump($file->isWritable()); echo ‘
echo ‘
isReadable()
‘; var_dump($file->isReadable()); echo ‘
echo ‘
isExecutable(
‘; var_dump($file->isExecutable()); echo ‘
echo ‘
‘; var_dump($file->isFile()); echo ‘
echo ‘
‘; var_dump($file->isDir()); echo ‘
echo ‘
‘; var_dump($file->isLink()); echo ‘
echo ‘
getFileInfo()
‘; var_dump($file->getFileInfo()); echo ‘
echo ‘
getPathInfo()
‘; var_dump($file->getPathInfo()); echo ‘
echo ‘
openFile()
‘; var_dump($file->openFile()); echo ‘
echo ‘
setFileClass()
‘; var_dump($file->setFileClass()); echo ‘
echo ‘
setInfoClass()
‘; var_dump($file->setInfoClass()); echo ‘
除了foreach循环外,还可以使用while循环:
/*** create a new iterator object ***/
$it = new DirectoryIterator('./');
/*** loop directly over the object ***/
while($it->valid())
echo $it->key().’ — ‘.$it->current().’‘;
/*** move to the next iteration ***/
$it->next();
如果要过滤所有子目录,可以在valid()方法中过滤:
/*** create a new iterator object ***/
$it = new DirectoryIterator('./');
/*** loop directly over the object ***/
while($it->valid())
/*** check if value is a directory ***/
if($it->isDir())
/*** echo the key and current value ***/
echo $it->key().’ — ‘.$it->current().’‘;
/*** move to the next iteration ***/
$it->next();
11. ArrayObject类
这个类可以将Array转化为object。
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
/*** create the array object ***/
$arrayObj = new ArrayObject($array);
/*** iterate over the array ***/
for($iterator = $arrayObj->getIterator();
/*** check if valid ***/
$iterator->valid();
/*** move to the next array member ***/
$iterator->next())
/*** output the key and current array value ***/
echo $iterator->key() . ‘ => ‘ . $iterator->current() . ‘‘;
增加一个元素:
$arrayObj->append(‘dingo’);
对元素排序:
$arrayObj->natcasesort();
显示元素的数量:
echo $arrayObj->count();
删除一个元素:
$arrayObj->offsetUnset(5);
某一个元素是否存在:
if ($arrayObj->offsetExists(3))
echo ‘Offset Exists‘;
更改某个位置的元素值:
$arrayObj->offsetSet(5, “galah”);
显示某个位置的元素值:
echo $arrayObj->offsetGet(4);
12. ArrayIterator类
这个类实际上是对ArrayObject类的补充,为后者提供遍历功能。
示例如下:
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
$object = new ArrayIterator($array);
foreach($object as $key=>$value)
echo $key.’ => ‘.$value.’‘;
catch (Exception $e)
echo $e->getMessage();
ArrayIterator类也支持offset类方法和count()方法:
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
$object = new ArrayIterator($array);
/*** check for the existence of the offset 2 ***/
if($object->offSetExists(2))
/*** set the offset of 2 to a new value ***/
$object->offSetSet(2, ‘Goanna’);
/*** unset the kiwi ***/
foreach($object as $key=>$value)
/*** check the value of the key ***/
if($object->offSetGet($key) === ‘kiwi’)
/*** unset the current key ***/
$object->offSetUnset($key);
echo ‘
‘.$key.’ – ‘.$value.’
‘.”\n”;
catch (Exception $e)
echo $e->getMessage();
13. RecursiveArrayIterator类和RecursiveIteratorIterator类
ArrayIterator类和ArrayObject类,只支持遍历一维数组。如果要遍历多维数组,必须先用RecursiveIteratorIterator生成一个Iterator,然后再对这个Iterator使用RecursiveIteratorIterator。
$array = array(
array('name'=>‘butch’, ‘sex’=>’m', ‘breed’=>’boxer’),
array(‘name’=>’fido’, ‘sex’=>’m', ‘breed’=>’doberman’),
array(‘name’=>’girly’,'sex’=>’f', ‘breed’=>’poodle’)
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key=>$value)
echo $key.’ — ‘.$value.’‘;
14. FilterIterator类
FilterIterator类可以对元素进行过滤,只要在accept()方法中设置过滤条件就可以了。
示例如下:
/*** a simple array ***/
$animals = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'NZ'=>‘kiwi’, ‘kookaburra’, ‘platypus’);
class CullingIterator extends FilterIterator{
/*** The filteriterator takes
a iterator as param: ***/
public function __construct( Iterator $it ){
parent::__construct( $it );
/*** check if key is numeric ***/
function accept(){
return is_numeric($this->key());
}/*** end of class ***/
$cull = new CullingIterator(new ArrayIterator($animals));
foreach($cull as $key=>$value)
echo $key.’ == ‘.$value.’‘;
下面是另一个返回质数的例子:
class PrimeFilter extends FilterIterator{
/*** The filteriterator takes
a iterator as param: ***/
public function __construct(Iterator $it){
parent::__construct($it);
/*** check if current value is prime ***/
function accept(){
if($this->current() % 2 != 1)
$x = sqrt($this->current());
while ($this->current() % $d != 0 &#038;&#038; $d < $x)
return (($this->current() % $d == 0 &#038;&#038; $this->current() != $d) * 1) == 0 ? true :
}/*** end of class ***/
/*** an array of numbers ***/
$numbers = range(456);
/*** create a new FilterIterator object ***/
$primes = new primeFilter(new ArrayIterator($numbers));
foreach($primes as $value)
echo $value.&#8217; is prime.&#8216;;
15. SimpleXMLIterator类
这个类用来遍历xml文件。
示例如下:
/*** a simple xml tree ***/
$xmlstring = <<<XML
Phascolarctidae
diprotodon
kingfisher
kookaburra
monotremes
funnel web
/*** a new simpleXML iterator object ***/
/*** a new simple xml iterator ***/
$it = new SimpleXMLIterator($xmlstring);
/*** a new limitIterator object ***/
foreach(new RecursiveIteratorIterator($it,1) as $name => $data)
echo $name.&#8217; &#8212; &#8216;.$data.&#8217;&#8216;;
catch(Exception $e)
echo $e->getMessage();
new RecursiveIteratorIterator($it,1)表示显示所有包括父元素在内的子元素。
显示某一个特定的元素值,可以这样写:
/*** a new simpleXML iterator object ***/
new SimpleXMLIterator($xmlstring);
foreach ( $sxi as $node )
foreach($node as $k=>$v)
echo $v->species.&#8217;&#8216;;
catch(Exception $e)
echo $e->getMessage();
相对应的while循环写法为:
$sxe = simplexml_load_string($xmlstring, 'SimpleXMLIterator');
for ($sxe->rewind(); $sxe->valid(); $sxe->next())
if($sxe->hasChildren())
foreach($sxe->getChildren() as $element=>$value)
echo $value->species.&#8217;&#8216;;
catch(Exception $e)
echo $e->getMessage();
最方便的写法,还是使用xpath:
/*** a new simpleXML iterator object ***/
new SimpleXMLIterator($xmlstring);
/*** set the xpath ***/
$foo = $sxi->xpath(&#8216;animal/category/species&#8217;);
/*** iterate over the xpath ***/
foreach ($foo as $k=>$v)
echo $v.&#8217;&#8216;;
catch(Exception $e)
echo $e->getMessage();
下面的例子,显示有namespace的情况:
/*** a simple xml tree ***/
$xmlstring = <<<XML
Phascolarctidae
Speed Hump
diprotodon
Road Runner
kingfisher
kookaburra
monotremes
funnel web
/*** a new simpleXML iterator object ***/
/*** a new simpleXML iterator object ***/
new SimpleXMLIterator($xmlstring);
$sxi-> registerXPathNamespace(&#8216;spec&#8217;, &#8216;http://www.exampe.org/species-title&#8217;);
/*** set the xpath ***/
$result = $sxi->xpath(&#8216;//spec:name&#8217;);
/*** get all declared namespaces ***/
foreach($sxi->getDocNamespaces(&#8216;animal&#8217;) as $ns)
echo $ns.&#8217;&#8216;;
/*** iterate over the xpath ***/
foreach ($result as $k=>$v)
echo $v.&#8217;&#8216;;
catch(Exception $e)
echo $e->getMessage();
增加一个节点:
$xmlstring = <<<XML
kookaburra
funnel web
/*** a new simpleXML iterator object ***/
new SimpleXMLIterator($xmlstring);
/*** add a child ***/
$sxi->addChild(&#8216;animal&#8217;, &#8216;Tiger&#8217;);
/*** a new simpleXML iterator object ***/
$new = new SimpleXmlIterator($sxi->saveXML());
/*** iterate over the new tree ***/
foreach($new as $val)
echo $val.&#8217;&#8216;;
catch(Exception $e)
echo $e->getMessage();
增加属性:
$xmlstring =<<<XML
kookaburra
funnel web
/*** a new simpleXML iterator object ***/
new SimpleXMLIterator($xmlstring);
/*** add an attribute with a namespace ***/
$sxi->addAttribute(&#8216;id:att1&#8242;, &#8216;good things&#8217;, &#8216;urn::test-foo&#8217;);
/*** add an attribute without a
namespace ***/
$sxi->addAttribute(&#8216;att2&#8242;, &#8216;no-ns&#8217;);
echo htmlentities($sxi->saveXML());
catch(Exception $e)
echo $e->getMessage();
16. CachingIterator类
这个类有一个hasNext()方法,用来判断是否还有下一个元素。
示例如下:
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
/*** create a new object ***/
$object = new CachingIterator(new ArrayIterator($array));
foreach($object as $value)
if($object->hasNext())
echo &#8216;,&#8217;;
catch (Exception $e)
echo $e->getMessage();
17. LimitIterator类
这个类用来限定返回结果集的数量和位置,必须提供offset和limit两个参数,与SQL命令中limit语句类似。
示例如下:
/*** the offset value ***/
$offset = 3;
/*** the limit of records to show ***/
$limit = 2;
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
$it = new LimitIterator(new ArrayIterator($array), $offset, $limit);
foreach($it as $k=>$v)
echo $it->getPosition().&#8217;&#8216;;
另一个例子是:
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
$it = new LimitIterator(new ArrayIterator($array));
$it->seek(5);
echo $it->current();
catch(OutOfBoundsException $e)
echo $e->getMessage() . &#8220;&#8220;;
18. SplFileObject类
这个类用来对文本文件进行遍历。
示例如下:
// iterate directly over the object
foreach( new SplFileObject(&/usr/local/apache/logs/access_log&) as $line)
// and echo each line of the file
echo $line.'&#8216;;
catch (Exception $e)
echo $e->getMessage();
返回文本文件的第三行,可以这样写:
$file = new SplFileObject("/usr/local/apache/logs/access_log");
$file->seek(3);
echo $file->current();
catch (Exception $e)
echo $e->getMessage();
[参考文献]
1. Introduction to Standard PHP Library (SPL), By Kevin Waterson
2. Introducing PHP 5&#8242;s Standard Library, By Harry Fuecks
3. The Standard PHP Library (SPL), By Ben Ramsey
4. SPL &#8211; Standard PHP Library Documentation
测试用例都是在tests下的文件中,用户可以建立自己的测试用例。采用此模块的好处就是可以调用其他模块的现成的方法来测试。
但是里面的方法是内置的,web页面只会测试这些方法。所以,把代码考到文件中方法来测试。
打开网页http://localhost/kohana/index.php/unit_test
页面上显示每个方法的测试结果,以及整体的测试数据,非常方便。
其他:针对kohana3的单元测试,可以从/ekingery/kohana-phpunit下载phpunit模块,方式和kohana2里面的差不多
Copyright&&&2016&vicenteforever
Theme summ by
and Powered by

我要回帖

更多关于 php好处 的文章

 

随机推荐