当前位置:Gxlcms > PHP教程 > 迭代器模式及其php实现(Yii框架)

迭代器模式及其php实现(Yii框架)

时间:2021-07-01 10:21:17 帮助过:25人阅读

迭代器模式是一种行为型模式,它是一种最简单也最常见的设计模式。它可以让使用者透过特定的接口巡访容器中的每一个元素而不用了解底层的实际操作。

适用性

在希望利用语言本身的遍历函数便利自定义结构时,例如PHP中的foreach函数

类图

2303.jpg

PHP实例

  1. <?php
  2. class sample implements Iterator {
  3. private $_items ;
  4. public function __construct(&$data) {
  5. $this->_items = $data;
  6. }
  7. public function current() {
  8. return current($this->_items);
  9. }
  10. public function next() {
  11. next($this->_items);
  12. }
  13. public function key() {
  14. return key($this->_items);
  15. }
  16. public function rewind() {
  17. reset($this->_items);
  18. }
  19. public function valid() {
  20. return ($this->current() !== FALSE);
  21. }
  22. }
  23. // client
  24. $data = array(1, 2, 3, 4, 5);
  25. $sa = new sample($data);
  26. foreach ($sa AS $key => $row) {
  27. echo $key, ' ', $row, '<br />';
  28. }
  29. ?>

在Yii框架中的实现:

在Yii框架中的我们可以看到其迭代器的实现,在collections目录下的CMapIterator.php文件中,其实现如下:

  1. class CMapIterator implements Iterator {
  2. /**
  3. * @var array the data to be iterated through
  4. */
  5. private $_d;
  6. /**
  7. * @var array list of keys in the map
  8. */
  9. private $_keys;
  10. /**
  11. * @var mixed current key
  12. */
  13. private $_key;
  14. /**
  15. * Constructor.
  16. * @param array the data to be iterated through
  17. */
  18. public function __construct(&$data) {
  19. $this->_d=&$data;
  20. $this->_keys=array_keys($data);
  21. }
  22. /**
  23. * Rewinds internal array pointer.
  24. * This method is required by the interface Iterator.
  25. */
  26. public function rewind() {
  27. $this->_key=reset($this->_keys);
  28. }
  29. /**
  30. * Returns the key of the current array element.
  31. * This method is required by the interface Iterator.
  32. * @return mixed the key of the current array element
  33. */
  34. public function key() {
  35. return $this->_key;
  36. }
  37. /**
  38. * Returns the current array element.
  39. * This method is required by the interface Iterator.
  40. * @return mixed the current array element
  41. */
  42. public function current() {
  43. return $this->_d[$this->_key];
  44. }
  45. /**
  46. * Moves the internal pointer to the next array element.
  47. * This method is required by the interface Iterator.
  48. */
  49. public function next() {
  50. $this->_key=next($this->_keys);
  51. }
  52. /**
  53. * Returns whether there is an element at current position.
  54. * This method is required by the interface Iterator.
  55. * @return boolean
  56. */
  57. public function valid() {
  58. return $this->_key!==false;
  59. }
  60. }
  61. $data = array('s1' => 11, 's2' => 22, 's3' => 33);
  62. $it = new CMapIterator($data);
  63. foreach ($it as $row) {
  64. echo $row, '<br />';
  65. }

这与之前的简单实现相比,其位置的变化是通过控制key来实现的,这种实现的作用是为了避免false作为数组值时无法迭代。

人气教程排行