這篇文章主要介紹了PHP基於SPL實現的迭代器模式,簡單描述了迭代器模式的概念、原理並結合執行個體形式分析了php使用SPL實現迭代器模式的相關操作技巧與注意事項,需要的朋友可以參考下
本文執行個體講述了PHP基於SPL實現的迭代器模式。分享給大家供大家參考,具體如下:
現在有這麼兩個類,Department部門類、Employee員工類:
//部門類class Department{ private $_name; private $_employees; function __construct($name){ $this->_name = $name; $this->employees = array(); } function addEmployee(Employee $e){ $this->_employees[] = $e; echo "員工{$e->getName()}被分配到{$this->_name}中去"; }}//員工類class Employee{ private $_name; function __construct($name){ $this->_name = $name; } function getName(){ return $this->_name; }}//應用:$lsgo = new Department('LSGO實驗室');$e1 = new Employee("小錦");$e2 = new Employee("小豬");$lsgo->addEmployee($e1);$lsgo->addEmployee($e2);
好了,現在LSGO實驗室已經有兩個部員了,現在我想把全部的部員都列出來,就是用迴圈來擷取部門的每個員工的詳情。
在這裡我們用PHP中的SPL標準庫提供的迭代器來實現。
《大話設計模式》中如是說:
迭代器模式:迭代器模式是遍曆集合的修正模式,迭代器模式的關鍵是將遍曆集合的任務交給一個叫做迭代器的對象,它的工作時遍曆並選擇序列中的對象,而用戶端程式員不必知道或關心該集合序列底層的結構。
迭代器模式的作用簡而言之:是使所有複雜資料結構的組件都可以使用迴圈來訪問
假如我們的對象要實現迭代,我們使這個類實現 Iterator(SPL標準庫提供),這是一個迭代器介面,為了實現該介面,我們必須實現以下方法:
current(),該函數返回當前資料項目
key(),該函數返回當前資料項目的鍵或者該項在列表中的位置
next(),該函數使資料項目的鍵或者位置前移
rewind(),該函數重設索引值或者位置
valid(),該函數返回 bool 值,表明當前鍵或者位置是否指向資料值
實現了 Iterator 介面和規定的方法後,PHP就能夠知道該類類型的對象需要迭代。
我們使用這種方式重構 Department 類:
class Department implements Iterator{ private $_name; private $_employees; private $_position;//標誌當前數組指標位置 function __construct($name) { $this->_name = $name; $this->employees = array(); $this->_position = 0; } function addEmployee(Employee $e) { $this->_employees[] = $e; echo "員工{$e->getName()}被分配到{$this->_name}中去"; } //實現 Iterator 介面要求實現的方法 function current() { return $this->_employees[$this->_position]; } function key() { return $this->_position; } function next() { $this->_position++; } function rewind() { $this->_position = 0; } function valid() { return isset($this->_employees[$this->_position]); }}//Employee 類同前//應用:$lsgo = new Department('LSGO實驗室');$e1 = new Employee("小錦");$e2 = new Employee("小豬");$lsgo->addEmployee($e1);$lsgo->addEmployee($e2);echo "LSGO實驗室部員情況:";//這裡其實遍曆的$_employeeforeach($lsgo as $val){ echo "部員{$val->getName()}";}
附加:
假如現在我們想要知道該部門有幾個員工,如果是數組的話,一個 count() 函數就 ok 了,那麼我們能不能像上面那樣把對象當作數組來處理?SPL標準庫中提供了 Countable 介面供我們使用:
class Department implements Iterator,Countable{ //前面同上 //實現Countable中要求實現的方法 function count(){ return count($this->_employees); }}//應用:echo "員工數量:";echo count($lsgo);
本文參考自《深入理解PHP進階技巧、物件導向與核心技術》