A brief discussion of the iterator pattern in PHP
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.
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
##Code implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
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 |
|
cursor mode.
1 2 3 4 5 6 7 |
|
- 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条了,不过也有可能会有失败的情况出现,这时,两个线程还会继续去发送那些上次发送不成功的信息,这样能够最大程度的确保发送的效率和到达率。
消息发送迭代器类图
完整源码: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 |
|
说明
- 其实就是两个迭代器,一个是正序一个是倒序,然后遍历数组
- 例子中我们还是对一个数组的操作,另外用两个类似于工厂方法模式的类来对迭代器进行封装
- 例子非常简单,但有时候这种用法也非常实用,比如一些搜索引擎排名的爬虫,多次确认某些关键词的排名,这时候我们就可以正着、反着来回进行验证
完整源码: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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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,

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

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

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 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.
