PHP iterator

zhaozj2021-02-16  52

Thanks, Bitbird to my guide

PHP IteratorPHP iterator

Author: Dejan Bosanac Translator: detrox

PHP arrays are generally a very powerful object container. But still, we can easily add a little more fuel to them. Imagine an iterator object as a kind of wrapper around our arrays. What we will try to accomplish here is to create unique interface for TRAVERSING ARRAYS AND TO Add A Little More Control Over How Our Objects Are Created and finaling. The PHP array is generally a very powerful object container. But we can still give him a turbocharged pressure. Imagine iterator objects as a group of packages. We have to try to complete a unique interface for traversing arrays and add extra additional controls on how to create objects, and finally support fool-style reads.

Interface interface

Iterator Has A Very Simple and Many Times Seen Interface. Iterative has a simple and frequent interface

With the interface like this you can easily perform all your daily tasks (such as traversing arrays) in any way you want and from any position you want. One advantage of using this approach against native PHP array functions is that you have one interface for all of your array tasks. you will not use foreach () construct in one case, list-each combination in other and yet next () and prev () functions in third any more. One more advantage is that now you can easily position on any Particular Element and Start Traversing from there. Here Are Few Code Examples: With this interface, we can easily perform our daily daily at any time, any way, any way we like. Transaction (like array traversal). One advantage of using this array function with this thing is that you have an interface to all array tasks [work]. You don't need to use the foreach () structure in a code, another combination of List and Each, and then use other places for a while to use next (), for a while to use Perv (). Another advantage is that you can now locate a certain element and can start traversing from here (in any way you want to have any way). There are some examples: Next ()) {Echo $ ELEM;} // Traverse Array In Reverse ORDER Relatives Iterator-> end (); while ($ elem = $ iterator-> previous ()) {Echo $ elem;} // traverse array from fiffh element on the fifth element to traverse $ iterator-> seek (5); while ($ elem = $ iterator-> next ()) {Echo $ ELM;}?>

OK, you say, this is all nice but there is nothing I can not do with combination of native PHP functions. Besides the fact that you are accessing all your arrays through unique interface, another (and most important) advantage is that Iterator's object Structure allows you to easy easily expand its functionality. OK, you said, this is very good, but there is nothing I can't use the original PHP function combination. In addition to this fact, you can access all of your arrays through the unique interface, and the advantage of (also the most important) Advantage is the object structure of the iterator to allow you to easily extend its function ObjectIterator Interface object Iterator interface

Often I have ended up in situations where my object methods had to return an array of some other object as a result. Usually that object is loaded from the database, but could be some other situation such as obtaining objects through some RPC protocol (XML- RPC, SOAP, ...) or endless other situation combinations that you experience every day. in this article we will focus on the first problem and briefly explain how to empower Iterator for the purpose you'd need. I often interrupted in my Object Method To return some other objects of other objects as a result [case]. Usually this object is read from the database, but it may be other conditions, such as obtaining a combination of other RPC protocols (XML-RPC, SOAP, ...) or the endless other case you have to experience every day. . In this article, we focus on the first problem and briefly explain how to achieve an iterator for your purpose.

Suppose that you are developing an address book for some large web application. Your address book will work with companies and persons. In addition, companies could have an endless number of employees (that are also kinds of persons). So far we have recognized two objects in our application:. Company and Person Also, it is clear that the company will have method getEmployees () that returns an array of Person objects There are a number of possible implementations of this method Here are some usual implementations:.. suppose you Develop a contact with a large web application. Your address book will work in the company and people. In addition, the company may have endless employees (this is also a kind of person). Now we recognize the two objects in the app: company and individuals. At the same time, it also clear that Company will have a method getEmployees () returns an array of objects. There are many implementations of this method. Here are some conventional implementations: First, you could write a query to collect all the ids of all the company employees Then you could make an array that contains all the objects and returns this array This would look something like this (supposing.. You Have A Database First, you can write a query to collect the ID of all company employees. Then you can make an array contain all objects to return to this array. This looks like this (assuming you have a database)

companyid"; $ stmt = execute_query ($ query); // creates statement object creation statement object $ this-> employees = array ( ); while ($ stmt) {$ this-> Employess [$ row-> id] = new person ($ row-> id); // Object Creation object creation} Return $ this-> Employees; }?>

And the usage would be: It is like this:

getEmployees (); foreach ($ Employees as $ ID => $ Employee) $ Employee-> AddvacationDays (3); // Object Usage Use of object?>

OK, these look like fairly obvious solutions. But, it has few big flaws. All objects are created but we do not know if we're going to use them all. There are two performance problems here. First accessing a relational database ( for creating these objects) can be very time expensive. and if the company has 500 employees and you need to access data for only 50, that is lot of time wasted. Imagine now, that we are loading these objects through RPC which is even slower . This could seriously affect application performance. Now, even if all objects are needed we do not need them at the same time, we need objects one by one as we are traversing the array. The solution above is a huge waste of resources ( Memory and Time). OK, these seem to be a clear and clear solution. However, it has some big defects. All objects are created but we don't know if they are needed. There are two performance problems here. First access a relational database (in order to create these objects) Time overhead. Secondly, if the company has 500 employees and you only need 50 data for it, this will be a lot of time. Now I imagine, we read these objects through a slower RPC. This will seriously affect the performance of the application. Now, even if all objects are needed, we need them at the same time, we need a movie [handling] object like we are traversing an array. The above solution case is a huge resource (memory and time) waste. The Solution To these Performance Problems Looks So Obvious. Let's return just an array of employee ids. The code 10: The solution to this performance problem seems to be so obvious. Let us only return an array containing the employee ID. The code looks like this:

companyid"; $ stmt = execute_query ($ query); // creates statement object $ this-> employees = array (); while ($ ROW = fetch_object ($ stmt) {$ this-> Employess [$ row-> id] = $ row-> id;} return $ this-> Employees;}?>

And the usage would be: User is like this:

getEmployees (); foreach ($ Employees AS $ ID) {$ Employee = New Employee ($ ID); // Object Creation $ Employee -> addVacationDays (3); // object usage}> This looks fine at the first sight We have saved time and memory, but another has arisen problem Suppose that the code for creating Employee object changes, for example you need to?.. add extra argument to the constructor or some extra initialization (these are things that are happening on real projects). in that case you'll need to modify your code in many places (wherever you have used getEmployees () method), And that is a question, looks quite good. We save time and memory, but another problem has appeared. Assuming to create a code for creating an employee object, for example, you need to add additional parameters or some additional initialization (this is a real project). On this issue, you will have to modify your code in many places (any place you use the getEmployees () method), this is a problem.

The third solution is to use an ObjectIterator class that is extended from Iterator. In this example we will see how easy it is to extend Iterator class to serve your purposes. When you are using ObjectIterator your getEmployee () function will stay the same as in SECOND SOLUTION. SO, WE Have Saved Objects Are Created and Everything Looks Just Fine. Now Let's Look At The Usage Code: The third solution is to use an object iterator class that extension it iterator. In this example we will see how easy it is easy for the expansion iterator for your purpose. When you use object iterators, your getEmployee () [should be the getEMPlyees () bar, which will be the same as the second solution. Therefore, we save our resources. There is no need to be created and everything looks fine. Now let's take a look at the code:

geteMployees (), "Employee"); while ($ Employee = $ iterator-> next ()) {$ Employee- > AddvacationDays (3);}?>

We See Now That The Object Creation Core Is Hidden In The ObjectIterator Class, SO IT IT IT IT ITS. We now see that the code created by the object is hidden in the object iterator class, so it is now easy to support changes. Implementation of ObjectIterator Implementation object iterator

The code for ObjectIterator is Quite Simple. The code of the object iterator is very simple.

Dejan Bosanac * /

Class ObjectIterator Extends itrator {

Var $ _Objectname;

/ ** * Constructor * Calls initialization method (@see Iterator :: _ initialize ()) * and do some specific configuration * @param array $ array array of object ids to be traversed * @param string $ objectName class of objects to be created * @access public * * Constructor * Call Initialization method (Reference Iterator :: _ Initialize ()) Do some special configuration * @ 参 参 数 $ array to traverse an array * @ parameter string $ Objectname To be created Object class * /

Function ObjectIterator ($ Array, $ Objectname) {$ this -> _ Initialize ($ array); $ this -> _ Objectname = $ ObjectName;}

/ ** * returns object with given id * @Param Object $ ID iDENTIFIER OF THE OBJECT * @return Object Next Object in the collection * @access private * * Use the gived ID back to the object * @ parameter object $ ID indicate an object * @ Return to the next object in the object * @ 存 私 私 * /

Function _FetchObject ($ ID) {Return New $ this -> _ Objectname ($ ID);}}?>

It has $ _objectName class member that represent class of the object that has to be returned by next () and previous () methods. The constructor sets this internal variable and calls an initialization function (defined in Iterator class). The most important thing is the _fetchObject () function. It encapsulates code for object creation. It is called from next () and previous () methods and takes object id as a parameter. So all your object creation code is localized here, thus making it easy to change and EXPAND. Class member $ _ObjectName Represents the class to which the object belongs must be returned by the next () and pervious () methods. The constructor sets internal variables and invokes the initialization function (already defined in the iterator class). The most important thing is the _FetchObject () function. He encapsulates the code created by the object. It is called by the next () and pervious () method and use the ID of the object as the parameter). This way, all your objects are here, so he is easy to change and extended and expands SO, Here Are ITRUCTIONS. First, Make Your Construction (Which Has to Have An Array As A Parameter) Which calls _initialize () Function from iterator class. second, override _fetchobject method method to do whatver you have to do to make your objects. And, That Would Be all. This is our way to create a new type of iterator. First, make your constructor (it has an array as a parameter), which calls from the iterator class _initialize () function. Second, overload _fetchobject method to do anything you must do for your object. this is all.

In Conclusion Conclusion

Iterator will not slow down your application in a way that it will need new hardware to run it. It has some overhead, but for that price you get clean and easy readable code that is flexible enough for future software enhancements. Iterator will not Any way to slow down your app unless it needs a new hardware to run. It has some load, but gives you clear-read code, which will make the extension of the software in the future very convenient

You can download the source program here

转载请注明原文地址:https://www.9cbs.com/read-25292.html

New Post(0)