迭代器模式,在不需要了解內部實現的前提下,遍歷一個聚合對象的內部元素。相比於傳統的編程模式,迭代器模式可以隱藏遍歷元素所需要的操作。
AllHacl.php
<?php
namespace Baobab;
class AllHacl implements \iterator{
protected $ids;protected $index;//當前位置
function __construct(){
$db = Factory::getDatabase('ha_cl');
$result = $db->query('select ID from ha_cl');
$this->ids = $result->fetch_all(MYSQLI_ASSOC);
}
/**
* 返回當前元素
*/
function current(){
$id = $this->ids[$this->index]['ID'];
return Factory::getHacl($id);
}
/**
* 向前移動到下一個元素
*/
function next(){
$this->index ++;
}
/**
* 返回到迭代器的第一個元素
*/
function rewind(){
$this->index = 0;
}
/**
* 查詢當前位置是否有數據
*/
function valid(){
return $this->index - count($this->ids);
}
/**
* 返回當前元素的鍵
*/
function key(){
return $this->index;
}
}
index.php
$hacls = new \Baobab\AllHacl();
foreach($hacls as $hacl){
var_dump($hacl->haclname);
}
Hacl類相關內容參考數據對象映射模式。http://www.cnblogs.com/tianxintian22/p/5232016.html