PHP SPL 介绍

简介

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的结果集,程序需要这样写:

  1. // Fetch the "aggregate structure"  
  2. $result = mysql_query("SELECT * FROM users");  
  3.   
  4. // Iterate over the structure  
  5. while ( $row = mysql_fetch_array($result) ) {  
  6.    // do stuff with the row here  
  7. }  
读出一个目录中的内容,需要这样写:
  1. // Fetch the "aggregate structure"  
  2. $dh = opendir('/home/harryf/files');  
  3.   
  4. // Iterate over the structure  
  5. while ( $file = readdir($dh) ) {  
  6.    // do stuff with the file here  
  7. }  
读出一个文本文件的内容,需要这样写:
  1. // Fetch the "aggregate structure"  
  2. $fh = fopen("/home/files/results.txt""r");  
  3.   
  4. // Iterate over the structure  
  5. while (!feof($fh)) {  
  6.   
  7.    $line = fgets($fh);  
  8.    // do stuff with the line here  
  9.   
  10. }  
上面三段代码,虽然处理的是不同的resource(资源),但是功能都是遍历结果集(loop over contents),因此Iterator的基本思想,就是将这三种不同的操作统一起来,用同样的命令界面,处理不同的资源。

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示例:

  1. /** 
  2. * An iterator for native PHP arrays, re-inventing the wheel 
  3. * 
  4. * Notice the "implements Iterator" - important! 
  5. */  
  6. class ArrayReloaded implements Iterator {  
  7.   
  8.    /** 
  9.    * A native PHP array to iterate over 
  10.    */  
  11.  private $array = array();  
  12.   
  13.    /** 
  14.    * A switch to keep track of the end of the array 
  15.    */  
  16.  private $valid = FALSE;  
  17.   
  18.    /** 
  19.    * Constructor 
  20.    * @param array native PHP array to iterate over 
  21.    */  
  22.  function __construct($array) {  
  23.    $this->array = $array;  
  24.  }  
  25.   
  26.    /** 
  27.    * Return the array "pointer" to the first element 
  28.    * PHP's reset() returns false if the array has no elements 
  29.    */  
  30.  function rewind(){  
  31.    $this->valid = (FALSE !== reset($this->array));  
  32.  }  
  33.   
  34.    /** 
  35.    * Return the current array element 
  36.    */  
  37.  function current(){  
  38.    return current($this->array);  
  39.  }  
  40.   
  41.    /** 
  42.    * Return the key of the current array element 
  43.    */  
  44.  function key(){  
  45.    return key($this->array);  
  46.  }  
  47.   
  48.    /** 
  49.    * Move forward by one 
  50.    * PHP's next() returns false if there are no more elements 
  51.    */  
  52.  function next(){  
  53.    $this->valid = (FALSE !== next($this->array));  
  54.  }  
  55.   
  56.    /** 
  57.    * Is the current element valid? 
  58.    */  
  59.  function valid(){  
  60.    return $this->valid;  
  61.  }  
  62. }  
使用方法如下:
  1. // Create iterator object  
  2. $colors = new ArrayReloaded(array ('red','green','blue',));  
  3.   
  4. // Iterate away!  
  5. foreach ( $colors as $color ) {  
  6.  echo $color."<br>";  
  7. }  
你也可以在foreach循环中使用key()方法:
  1. // Display the keys as well  
  2. foreach ( $colors as $key => $color ) {  
  3.  echo "$key: $color<br>";  
  4. }  
除了foreach循环外,也可以使用while循环:
  1. // Reset the iterator - foreach does this automatically  
  2. $colors->rewind();  
  3.   
  4. // Loop while valid  
  5. while ( $colors->valid() ) {  
  6.   
  7.    echo $colors->key().": ".$colors->current()."";  
  8.    $colors->next();  
  9.   
  10. }  
根据测试,while循环要稍快于foreach循环,因为运行时少了一层中间调用。

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接口的实例:

  1. /** 
  2. * A class that can be used like an array 
  3. */  
  4. class Article implements ArrayAccess {  
  5.   
  6.  public $title;  
  7.   
  8.  public $author;  
  9.   
  10.  public $category;    
  11.   
  12.  function __construct($title,$author,$category) {  
  13.    $this->title = $title;  
  14.    $this->author = $author;  
  15.    $this->category = $category;  
  16.  }  
  17.   
  18.  /** 
  19.  * Defined by ArrayAccess interface 
  20.  * Set a value given it's key e.g. $A['title'] = 'foo'; 
  21.  * @param mixed key (string or integer) 
  22.  * @param mixed value 
  23.  * @return void 
  24.  */  
  25.  function offsetSet($key$value) {  
  26.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  27.      $this->{$key} = $value;  
  28.    }  
  29.  }  
  30.   
  31.  /** 
  32.  * Defined by ArrayAccess interface 
  33.  * Return a value given it's key e.g. echo $A['title']; 
  34.  * @param mixed key (string or integer) 
  35.  * @return mixed value 
  36.  */  
  37.  function offsetGet($key) {  
  38.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  39.      return $this->{$key};  
  40.    }  
  41.  }  
  42.   
  43.  /** 
  44.  * Defined by ArrayAccess interface 
  45.  * Unset a value by it's key e.g. unset($A['title']); 
  46.  * @param mixed key (string or integer) 
  47.  * @return void 
  48.  */  
  49.  function offsetUnset($key) {  
  50.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  51.      unset($this->{$key});  
  52.    }  
  53.  }  
  54.   
  55.  /** 
  56.  * Defined by ArrayAccess interface 
  57.  * Check value exists, given it's key e.g. isset($A['title']) 
  58.  * @param mixed key (string or integer) 
  59.  * @return boolean 
  60.  */  
  61.  function offsetExists($offset) {  
  62.    return array_key_exists($offset,get_object_vars($this));  
  63.  }  
  64.   
  65. }  
使用方法如下:
  1. // Create the object  
  2. $A = new Article('SPL Rocks','Joe Bloggs''PHP');  
  3.   
  4. // Check what it looks like  
  5. echo 'Initial State:<div>';  
  6. print_r($A);  
  7. echo '</div>';  
  8.   
  9. // Change the title using array syntax  
  10. $A['title'] = 'SPL _really_ rocks';  
  11.   
  12. // Try setting a non existent property (ignored)  
  13. $A['not found'] = 1;  
  14.   
  15. // Unset the author field  
  16. unset($A['author']);  
  17.   
  18. // Check what it looks like again  
  19. echo 'Final State:<div>';  
  20. print_r($A);  
  21. 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那样操作。

你还可以在读取数据时,增加程序内部的逻辑:

  1. function offsetGet($key) {  
  2.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  3.      return strtolower($this->{$key});  
  4.    }  
  5.  }  

IteratorAggregate接口

但是,虽然$A可以像数组那样操作,却无法使用foreach遍历,除非实现了前面提到的Iterator接口。

另一个解决方法是,有时会需要将数据和遍历部分分开,这时就可以实现IteratorAggregate接口。它规定了一个getIterator()方法,返回一个使用Iterator接口的object。

还是以上一节的Article类为例:

  1. class Article implements ArrayAccess, IteratorAggregate {  
  2.   
  3. /** 
  4.  * Defined by IteratorAggregate interface 
  5.  * Returns an iterator for for this object, for use with foreach 
  6.  * @return ArrayIterator 
  7.  */  
  8.  function getIterator() {  
  9.    return new ArrayIterator($this);  
  10.  }  
使用方法如下:
  1. $A = new Article('SPL Rocks','Joe Bloggs''PHP');  
  2.   
  3. // Loop (getIterator will be called automatically)  
  4. echo 'Looping with foreach:<div>';  
  5. foreach ( $A as $field => $value ) {  
  6.  echo "$field : $value<br>";  
  7. }  
  8. echo '</div>';  
  9.   
  10. // Get the size of the iterator (see how many properties are left)  
  11. 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类

这个类用来查看一个目录中的所有文件和子目录:

  1. <?php  
  2.   
  3. try{  
  4.   /*** class create new DirectoryIterator Object ***/  
  5.     foreach ( new DirectoryIterator('./'as $Item )  
  6.         {  
  7.         echo $Item.'<br />';  
  8.         }  
  9.     }  
  10. /*** if an exception is thrown, catch it here ***/  
  11. catch(Exception $e){  
  12.     echo 'No files Found!<br />';  
  13. }  
  14. ?>  

ArrayObject类

这个类可以将Array转化为object:

  1. <?php  
  2.   
  3. /*** a simple array ***/  
  4. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  5.   
  6. /*** create the array object ***/  
  7. $arrayObj = new ArrayObject($array);  
  8.   
  9. /*** iterate over the array ***/  
  10. for($iterator = $arrayObj->getIterator();  
  11.    /*** check if valid ***/  
  12.    $iterator->valid();  
  13.    /*** move to the next array member ***/  
  14.    $iterator->next())  
  15.     {  
  16.     /*** output the key and current array value ***/  
  17.     echo $iterator->key() . ' => ' . $iterator->current() . '<br />';  
  18.     }  
  19. ?>  

增加一个元素:

$arrayObj->append('dingo');

对元素排序:

$arrayObj->natcasesort();

显示元素的数量:

echo $arrayObj->count();

删除一个元素:

$arrayObj->offsetUnset(5);

某一个元素是否存在:

 $arrayObj->offsetExists(3)
    

更改某个位置的元素值:

 $arrayObj->offsetSet(5, "galah");

显示某个位置的元素值:

echo $arrayObj->offsetGet(4);

ArrayIterator类

这个类实际上是对ArrayObject类的补充,为后者提供遍历功能。

示例如下:

  1. <?php  
  2. /*** a simple array ***/  
  3. $array = array('koala''kangaroo''wombat''wallaby''emu');  
  4.   
  5. try {  
  6.     $object = new ArrayIterator($array);  
  7.     foreach($object as $key=>$value)  
  8.         {  
  9.         echo $key.' => '.$value.'<br />';  
  10.         }  
  11.     }  
  12. catch (Exception $e)  
  13.     {  
  14.     echo $e->getMessage();  
  15.     }  
  16. ?>  

FilterIterator类

FilterIterator类可以对元素进行过滤,只要在accept()方法中设置过滤条件就可以了。

示例如下:

  1. <?php  
  2. /*** a simple array ***/  
  3. $animals = array('koala''kangaroo''wombat''wallaby''emu''NZ'=>'kiwi''kookaburra''platypus');  
  4.   
  5. class CullingIterator extends FilterIterator{  
  6.   
  7. /*** The filteriterator takes  a iterator as param: ***/  
  8. public function __construct( Iterator $it ){  
  9.   parent::__construct( $it );  
  10. }  
  11.   
  12. /*** check if key is numeric ***/  
  13. function accept(){  
  14.   return is_numeric($this->key());  
  15. }  
  16.   
  17. }/*** end of class ***/  
  18. $cull = new CullingIterator(new ArrayIterator($animals));  
  19.   
  20. foreach($cull as $key=>$value)  
  21.     {  
  22.     echo $key.' == '.$value.'<br />';  
  23.     }  
  24. ?>  

以上介绍了SPL常用的一些接口和类,更多请参考PHP手册

发布了25 篇原创文章 · 获赞 4 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章