欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP基于SPL实现的迭代器步骤详解

程序员文章站 2022-04-06 16:36:06
...
这次给大家带来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实验室部员情况:";
//这里其实遍历的$_employee
foreach($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);

相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!

推荐阅读:

php7操作MongoDB增删改查步骤详解

PHP工厂方法设计模式案例详解

以上就是PHP基于SPL实现的迭代器步骤详解的详细内容,更多请关注其它相关文章!

相关标签: php 详解 步骤