一、简介
- 什么是SPL?
Standard PHP Library(PHP标准库)
SPL是用于解决典型问题(standard problems)的一组接口与类的集合。
目前在使用中,SPL更多地被看作是一种使object(物体)模仿array(数组)行为的interfaces和classes。 什么是Iterator? (迭代器)
SPL的核心概念就是Iterator。这指的是一种Design Pattern。
通俗地说,Iterator能够使许多不同的数据结构,都能有统一的操作界面,比如一个数据库的结果集、同一个目录中的文件集、或者一个文本中每一行构成的集合。
如果按照普通情况,遍历一个MySQL的结果集,程序需要这样写:
// Fetch the "aggregate structure"
$result = mysql_query("SELECT * FROM users");
// Iterate over the structure
while ( $row = mysql_fetch_array($result) ) {
// do stuff with the row here
}
读出一个目录中的内容,需要这样写:
// Fetch the "aggregate structure"
$dh = opendir('/home/harryf/files');
// Iterate over the structure
while ( $file = readdir($dh) ) {
// do stuff with the file here
}
读出一个文本文件的内容,需要这样写:
// Fetch the "aggregate structure"
$fh = fopen("/home/hfuecks/files/results.txt", "r");
// Iterate over the structure
while (!feof($fh)) {
$line = fgets($fh);
// do stuff with the line here
}
上面三段代码,虽然处理的是不同的resource(资源),但是功能都是遍历结果集(loop over contents),因此Iterator的基本思想,就是将这三种不同的操作统一起来,用同样的命令界面,处理不同的资源。