PHP设计模式之迭代器模式

Table of Contents

定义

让你能在不暴露集合底层表现形式 (列表、 栈和树等) 的情况下遍历集合中所有的对象元素。PHP 标准库 (SPL) 定义了一个最适合此模式的接口迭代器!往往也需要实现 Countable 接口,允许在迭代器对象上使用 count($object) 方法。

实现

class User
{
   private $name = '';
   private $age = 0;
   private $job = '';

   public function __construct(string $name, int $age, string $job)
  {
       $this->name = $name;
       $this->age  = $age;
       $this->job  = $job;
  }

   public function getDesc ()
  {
       return $this->name . '|' . $this->age . '|' . $this->job . PHP_EOL;
  }
}

class UserList implements \Iterator, \Countable
{
   private $users = null;
   private $currentIndex = 0;

   public function addUsers (User $user)
  {
       $this->users[] = $user;
  }

   public function current()
  {
       return $this->users[$this->currentIndex];
  }

   public function next()
  {
       $this->currentIndex++;
  }

   public function key()
  {
       return $this->currentIndex;
  }

   public function valid ()
  {
       return isset($this->users[$this->currentIndex]);
  }

   public function rewind ()
  {
       $this->currentIndex = 0;
  }

   public function count ()
  {
       return count($this->users);
  }
}

测试代码如下:

$users = new UserList();
$users->addUsers(new User('james', '36', 'player'));
$users->addUsers(new User('jay', '42', 'singer'));
$users->addUsers(new User('sinwa', '33', 'driver'));
$users->addUsers(new User('liming', '76', 'farmer'));

foreach ($users as $user) {
  echo $user->getDesc();
}

当对象实现了PHP自带的Iterator接口后,我们就可以使用foreach来遍历该对象实例。