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标准库内置的迭代器机制来完成该任务。
《大话设计模式》对此有如下描述:
迭代器模式是一种成熟的集合遍历方案。其核心在于将遍历职责委托给专门的迭代器对象,由它负责遍历并筛选序列中的元素,而客户端无需知晓集合底层的结构细节。
简而言之,迭代器模式的作用是让各种复杂数据结构的组件都能通过统一的循环方式进行访问。
若需让对象具备迭代能力,可使其实现SPL提供的Iterator接口。为实现此接口,必须覆写以下方法:
current():返回当前数据项。
key():返回当前数据项的键或其在列表中的位置索引。
next():将数据项的键或位置指针向前移动。
rewind():重置内部键值或位置指针至初始状态。
valid():返回布尔值,指示当前键或位置是否指向有效的数据值。
完成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实验室部员情况:";
//这里其实遍历的$_employee
foreach($lsgo as $val){
echo "部员{$val->getName()}";
}
补充说明:
若需统计部门员工数量,数组通常直接使用count()函数即可。能否让对象也像数组一样被处理?SPL标准库提供了Countable接口以满足这一需求。
class Department implements Iterator,Countable{
//前面同上
//实现Countable中要求实现的方法
function count(){
return count($this->_employees);
}
}
//应用:
echo "员工数量:";
echo count($lsgo);
本文内容参考自《深入理解PHP高级技巧、面向对象与核心技术》。
希望本文所述内容能对读者的PHP程序设计工作提供帮助。