Table of Contents
Gof class diagram and explanation
实例
Home Backend Development PHP Problem A brief discussion of the iterator pattern in PHP

A brief discussion of the iterator pattern in PHP

Jul 01, 2021 pm 07:03 PM
php Design Patterns iterator pattern

In the previous article "In-depth analysis of the observer pattern in PHP" we introduced the observer pattern in PHP. The following article will take you to understand the iterator pattern in PHP.

A brief discussion of the iterator pattern in PHP

When talking about this pattern, we have to mention loop statements. In "Dahua Design Pattern", the author said that the learning significance of this model is now greater than the practical significance. Why is this? Of course, it was because of foreach. Any language has this kind of similar syntax that can quickly and easily traverse arrays and objects, thus allowing the iterator pattern to slowly become a passer-by from the star among the 23 major design patterns. Especially our PHP language, the power of PHP lies in its flexible operation of arrays. It is a hashmap structure. Naturally, there are various convenient array operation syntaxes, and foreach is also our most commonly used statement, even better than for. Also commonly used.

Gof class diagram and explanation

GoF definition: Provides a method to sequentially access each element in an aggregate object without exposing it The internal representation of the object

GoF class diagram

A brief discussion of the iterator pattern in PHP

##Code implementation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

interface Aggregate

{

    public function CreateIterator();

}

 

class ConcreteAggregate implements Aggregate

{

    public function CreateIterator()

    {

        $list = [

            "a",

            "b",

            "c",

            "d",

        ];

        return new ConcreteIterator($list);

    }

}

Copy after login

The first is the aggregate class, which is a class that can be iterated. Because I am an object-oriented design pattern, the iterator pattern is aimed at iterating the contents of a class. Here, in fact, we just simulated an array and handed it over to the iterator.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

interface MyIterator

{

    public function First();

    public function Next();

    public function IsDone();

    public function CurrentItem();

}

 

class ConcreteIterator implements MyIterator

{

    private $list;

    private $index;

    public function __construct($list)

    {

        $this->list = $list;

        $this->index = 0;

    }

    public function First()

    {

        $this->index = 0;

    }

 

    public function Next()

    {

        $this->index++;

    }

 

    public function IsDone()

    {

        return $this->index >= count($this->list);

    }

 

    public function CurrentItem()

    {

        return $this->list[$this->index];

    }

}

Copy after login

The iterator makes its debut and mainly implements four methods to operate on collection data. A bit like what you do with cursors when learning data structures or databases. Use First() and Next() to move the cursor, use CurrentItem() to obtain the data content of the current cursor, and use IsDone() to confirm whether there is next data. Therefore, this mode is also called

cursor mode.

1

2

3

4

5

6

7

$agreegate = new ConcreteAggregate();

$iterator = $agreegate->CreateIterator();

 

while (!$iterator->IsDone()) {

    echo $iterator->CurrentItem(), PHP_EOL;

    $iterator->Next();

}

Copy after login

The client can directly use while to operate.

    Everyone must be curious, why is our iterator interface class not named Iterator? Try it and you will know that PHP has prepared this interface for us. After implementing it, you can use foreach to use this class that implements the Iterator interface. Isn't it very advanced? Let's finally look at the use of this class.
  • Didn’t you agree to traverse the class? Why pass an array back and forth? Students who have developed Java must know that in a JavaBean named Object class, a variable of List type, such as List myList, is written to represent the current collection of objects. After adding data to this List during use, you can directly use Object.myList to obtain a set of data next time. For example, the json array content obtained from the interface can be stored in a Bean. At this time, we can use an iterator to operate only on the array inside our own object!
  • The above Java content is actually what the author often uses when doing Android development. Sometimes the JavaBean of the database will also have this kind of array to store foreign keys. But it is generally rarely used in PHP, because most AR objects in PHP are slightly different from the Bean concept in Java. Interested students can learn more!

Our mobile phone factory is amazing. It has assembled a production line by itself. What is this production line mainly used for? We have handed over the molding machine to Foxconn, and our line is for painting mobile phones. When we put all the delivered mobile phones (Aggregate) into different production lines (Iterator), they will help us paint the color of the current production line one by one. Isn’t it very powerful! ! Technology is not just about changing shells. If this line is still there, we can do other things, such as adding some lanyards. Anyway, as long as I can pass one by one, I can put things on. Do you think it will work? Easy to use! !

Full code: https://github.com/zhangyue0503/designpatterns-php/blob/master/07.iterator/source/iterator.php

实例

实例还是围绕着我们的短信发送来看。这一次,我们的业务需求是尽快的发一批通知短信给用户,因为活动的时候可不等人啊。在之前我们会使用多个脚本来把用户手机号分成多组来进行发送。现在我们可以用swoole来直接多线程的发送。所要达到的效果其实就是为了快速的把成百上千的短信发完。这个时候我们也会做一些策略,比如数据库里是100条要送的短信,有个字段是发送状态,一个线程正序的发,一个线程倒序的发,当正序和倒序都发送到50条的时候其实已经同步的发完这100条了,不过也有可能会有失败的情况出现,这时,两个线程还会继续去发送那些上次发送不成功的信息,这样能够最大程度的确保发送的效率和到达率。

消息发送迭代器类图

A brief discussion of the iterator pattern in PHP

完整源码:https://github.com/zhangyue0503/designpatterns-php/blob/master/07.iterator/source/iterator-msg.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

<?php

 

interface MsgIterator

{

    public function First();

    public function Next();

    public function IsDone();

    public function CurrentItem();

}

 

// 正向迭代器

class MsgIteratorAsc implements MsgIterator

{

    private $list;

    private $index;

    public function __construct($list)

    {

        $this->list = $list;

        $this->index = 0;

    }

    public function First()

    {

        $this->index = 0;

    }

 

    public function Next()

    {

        $this->index++;

    }

 

    public function IsDone()

    {

        return $this->index >= count($this->list);

    }

 

    public function CurrentItem()

    {

        return $this->list[$this->index];

    }

}

 

// 反向迭代器

class MsgIteratorDesc implements MsgIterator

{

    private $list;

    private $index;

    public function __construct($list)

    {

        // 反转数组

        $this->list = array_reverse($list);

        $this->index = 0;

    }

    public function First()

    {

        $this->index = 0;

    }

 

    public function Next()

    {

        $this->index++;

    }

 

    public function IsDone()

    {

        return $this->index >= count($this->list);

    }

 

    public function CurrentItem()

    {

        return $this->list[$this->index];

    }

}

 

interface Message

{

    public function CreateIterator($list);

}

 

class MessageAsc implements Message

{

    public function CreateIterator($list)

    {

        return new MsgIteratorAsc($list);

    }

}

class MessageDesc implements Message

{

    public function CreateIterator($list)

    {

        return new MsgIteratorDesc($list);

    }

}

 

// 要发的短信号码列表

$mobileList = [

    &#39;13111111111&#39;,

    &#39;13111111112&#39;,

    &#39;13111111113&#39;,

    &#39;13111111114&#39;,

    &#39;13111111115&#39;,

    &#39;13111111116&#39;,

    &#39;13111111117&#39;,

    &#39;13111111118&#39;,

];

 

// A服务器脚本或使用swoole发送正向的一半

$serverA = new MessageAsc();

$iteratorA = $serverA->CreateIterator($mobileList);

 

while (!$iteratorA->IsDone()) {

    echo $iteratorA->CurrentItem(), PHP_EOL;

    $iteratorA->Next();

}

 

// B服务器脚本或使用swoole同步发送反向的一半

$serverB = new MessageDesc();

$iteratorB = $serverB->CreateIterator($mobileList);

 

while (!$iteratorB->IsDone()) {

    echo $iteratorB->CurrentItem(), PHP_EOL;

    $iteratorB->Next();

}

Copy after login

说明

  • 其实就是两个迭代器,一个是正序一个是倒序,然后遍历数组
  • 例子中我们还是对一个数组的操作,另外用两个类似于工厂方法模式的类来对迭代器进行封装
  • 例子非常简单,但有时候这种用法也非常实用,比如一些搜索引擎排名的爬虫,多次确认某些关键词的排名,这时候我们就可以正着、反着来回进行验证

完整源码:https://github.com/zhangyue0503/designpatterns-php/blob/master/06.observer/source/spl_observer.php

彩蛋

PHP中的Iterator接口已经为我们准备好了一套标准的Iterator模式的实现,而且(这里需要画重点),实现这个接口的类可以用foreach来遍历哦!

文档:https://www.php.net/manual/zh/class.iterator.php

源码:https://github.com/zhangyue0503/designpatterns-php/blob/master/07.iterator/source/iterator-php.php

文档中相关的接口都可以看看,更重要的是,PHP的SPL扩展中,也为我们准备了很多常用的迭代器封装。要知道,面试的时候要是能说出这里面的几个来,那面试官可是也会刮目相看的哦!

SPL迭代器:https://www.php.net/manual/zh/spl.iterators.php

本文转载自:https://juejin.cn/post/6844903937921777671

作者:硬核项目经理

推荐学习:《PHP视频教程

The above is the detailed content of A brief discussion of the iterator pattern in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles