簡介
SPL
SPL是Standard PHP Library(PHP標準庫)的縮寫。
根據官方定義,它是“a collection of interfaces and classes that are meant to solve standard problems”。但是,目前在使用中,SPL更多地被看作是一種使object(物體)模仿array(數組)行爲的interfaces和classes。
Iterator
SPL的核心概念就是Iterator。這指的是一種Design Pattern,根據《Design Patterns》一書的定義,Iterator的作用是“provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.”
wikipedia中說,"an iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation".……"the iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation".
通俗地說,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/files/results.txt", "r");
- // Iterate over the structure
- while (!feof($fh)) {
- $line = fgets($fh);
- // do stuff with the line here
- }
SPL 接口
Iterator接口
SPL規定,所有實現了Iterator接口的class,都可以用在foreach Loop中。Iterator界面中包含5個必須部署的方法:
* current()
This method returns the current index’s value. You are solely
responsible for tracking what the current index is as the
interface does not do this for you.* key()
This method returns the value of the current index’s key. For
foreach loops this is extremely important so that the key
value can be populated.* next()
This method moves the internal index forward one entry.
* rewind()
This method should reset the internal index to the first element.
* valid()
This method should return true or false if there is a current
element. It is called after rewind() or next().
下面就是一個部署了Iterator界面的class示例:
- /**
- * An iterator for native PHP arrays, re-inventing the wheel
- *
- * Notice the "implements Iterator" - important!
- */
- class ArrayReloaded implements Iterator {
- /**
- * A native PHP array to iterate over
- */
- private $array = array();
- /**
- * A switch to keep track of the end of the array
- */
- private $valid = FALSE;
- /**
- * Constructor
- * @param array native PHP array to iterate over
- */
- function __construct($array) {
- $this->array = $array;
- }
- /**
- * Return the array "pointer" to the first element
- * PHP's reset() returns false if the array has no elements
- */
- function rewind(){
- $this->valid = (FALSE !== reset($this->array));
- }
- /**
- * Return the current array element
- */
- function current(){
- return current($this->array);
- }
- /**
- * Return the key of the current array element
- */
- function key(){
- return key($this->array);
- }
- /**
- * Move forward by one
- * PHP's next() returns false if there are no more elements
- */
- function next(){
- $this->valid = (FALSE !== next($this->array));
- }
- /**
- * Is the current element valid?
- */
- function valid(){
- return $this->valid;
- }
- }
- // Create iterator object
- $colors = new ArrayReloaded(array ('red','green','blue',));
- // Iterate away!
- foreach ( $colors as $color ) {
- echo $color."<br>";
- }
- // Display the keys as well
- foreach ( $colors as $key => $color ) {
- echo "$key: $color<br>";
- }
- // Reset the iterator - foreach does this automatically
- $colors->rewind();
- // Loop while valid
- while ( $colors->valid() ) {
- echo $colors->key().": ".$colors->current()."";
- $colors->next();
- }
ArrayAccess接口
實現ArrayAccess接口,可以使得object像array那樣操作。ArrayAccess接口包含四個必須部署的方法:
* offsetExists($offset)
This method is used to tell php if there is a value
for the key specified by offset. It should return
true or false.
* offsetGet($offset)
This method is used to return the value specified
by the key offset.
* offsetSet($offset, $value)
This method is used to set a value within the object,
you can throw an exception from this function for a
read-only collection.
* offsetUnset($offset)
This method is used when a value is removed from
an array either through unset() or assigning the key
a value of null. In the case of numerical arrays, this
offset should not be deleted and the array should
not be reindexed unless that is specifically the
behavior you want.
下面就是一個實現ArrayAccess接口的實例:
- /**
- * A class that can be used like an array
- */
- class Article implements ArrayAccess {
- public $title;
- public $author;
- public $category;
- function __construct($title,$author,$category) {
- $this->title = $title;
- $this->author = $author;
- $this->category = $category;
- }
- /**
- * Defined by ArrayAccess interface
- * Set a value given it's key e.g. $A['title'] = 'foo';
- * @param mixed key (string or integer)
- * @param mixed value
- * @return void
- */
- function offsetSet($key, $value) {
- if ( array_key_exists($key,get_object_vars($this)) ) {
- $this->{$key} = $value;
- }
- }
- /**
- * Defined by ArrayAccess interface
- * Return a value given it's key e.g. echo $A['title'];
- * @param mixed key (string or integer)
- * @return mixed value
- */
- function offsetGet($key) {
- if ( array_key_exists($key,get_object_vars($this)) ) {
- return $this->{$key};
- }
- }
- /**
- * Defined by ArrayAccess interface
- * Unset a value by it's key e.g. unset($A['title']);
- * @param mixed key (string or integer)
- * @return void
- */
- function offsetUnset($key) {
- if ( array_key_exists($key,get_object_vars($this)) ) {
- unset($this->{$key});
- }
- }
- /**
- * Defined by ArrayAccess interface
- * Check value exists, given it's key e.g. isset($A['title'])
- * @param mixed key (string or integer)
- * @return boolean
- */
- function offsetExists($offset) {
- return array_key_exists($offset,get_object_vars($this));
- }
- }
- // Create the object
- $A = new Article('SPL Rocks','Joe Bloggs', 'PHP');
- // Check what it looks like
- echo 'Initial State:<div>';
- print_r($A);
- echo '</div>';
- // 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:<div>';
- print_r($A);
- echo '</div>';
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});
- }
- }
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:<div>';
- foreach ( $A as $field => $value ) {
- echo "$field : $value<br>";
- }
- echo '</div>';
- // 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
RecursiveIterator接口
這個接口用於遍歷多層數據,它繼承了Iterator界面,因而也具有標準的current()、key()、next()、 rewind()和valid()方法。同時,它自己還規定了getChildren()和hasChildren()方法。
The getChildren() method must return an object that implements RecursiveIterator.
SPL 類
DirectoryIterator類
這個類用來查看一個目錄中的所有文件和子目錄:
- <?php
- try{
- /*** class create new DirectoryIterator Object ***/
- foreach ( new DirectoryIterator('./') as $Item )
- {
- echo $Item.'<br />';
- }
- }
- /*** if an exception is thrown, catch it here ***/
- catch(Exception $e){
- echo 'No files Found!<br />';
- }
- ?>
ArrayObject類
這個類可以將Array轉化爲object:
- <?php
- /*** 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() . '<br />';
- }
- ?>
增加一個元素:
$arrayObj->append('dingo');
對元素排序:
$arrayObj->natcasesort();
顯示元素的數量:
echo $arrayObj->count();
刪除一個元素:
$arrayObj->offsetUnset(5);
某一個元素是否存在:
$arrayObj->offsetExists(3)
更改某個位置的元素值:
$arrayObj->offsetSet(5, "galah");
顯示某個位置的元素值:
echo $arrayObj->offsetGet(4);
ArrayIterator類
這個類實際上是對ArrayObject類的補充,爲後者提供遍歷功能。
示例如下:
- <?php
- /*** a simple array ***/
- $array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu');
- try {
- $object = new ArrayIterator($array);
- foreach($object as $key=>$value)
- {
- echo $key.' => '.$value.'<br />';
- }
- }
- catch (Exception $e)
- {
- echo $e->getMessage();
- }
- ?>
FilterIterator類
FilterIterator類可以對元素進行過濾,只要在accept()方法中設置過濾條件就可以了。
示例如下:
- <?php
- /*** 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.'<br />';
- }
- ?>
以上介紹了SPL常用的一些接口和類,更多請參考PHP手冊。