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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章