PHP SPL use method Auto load and iterator

Source: Internet
Author: User
Tags autoload spl zend zend framework

Spl,php Standards Library (standard PHP library), which has built-in components and interfaces from PHP 5.0, and is gradually maturing from the PHP5.3. SPL is actually built into all PHP5 development environments without any setup.
It seems that many PHP developers are not using it, or even unheard of. The reason for this can be traced to its spring snow-like documentation, which makes you ignore "its existence". This gem of SPL, like the "Heart of the Ocean" of the Titanic, was sunk into the sea. And now it should be picked up by us and put it in its rightful place, and that's the point of this article.
So, what does SPL offer?
SPL extends the PHP engine, such as interfaces such as arrayaccess, countable, and seekableiterator, which are used to manipulate objects in the form of arrays. At the same time, you can use other iterators such as Recursiveiterator, arrayobejcts, and so on to perform iterative operations on the data.
It also includes several objects such as Exceptions, Splobserver, spltorage, and helper functions for Splautoloadregister, splclasses, iteratorapply, and so on (helper functions), which is used to overload the corresponding function.
These tools converge like a multi-functional Swiss Army knife and use them to improve PHP's code efficiency in a qualitative sense. So, how do we play its power?
Heavy Duty Autoloader
If you are a "textbook programmer", then you are guaranteed to know how to use __autoload instead of includes/requires to load the corresponding class lazily, right?
But for a long time, you will find yourself in a dilemma, first of all you have to ensure that your class files must be in the specified file path, for example in the Zend framework you must use "_" to split the class, method name (How do you solve this problem?). )。
Another problem is that when the project becomes more and more complex, the logic within the __autoload becomes more complex. In the end, you will even add the exception judgment and write all the logic loaded into the class.
As we all know, "eggs cannot be placed in a basket", using SPL to separate __autoload loading logic. Just write your own autoload function and reload it with the function provided by SPL.
For example the above Zend framework problem, you can overload Zend Loader corresponding method, if it does not find the corresponding class, then use your previously defined function.

The code is as follows:


<?php
Class Myloader {
public static function Doautoload ($class) {
This module corresponds to the autoload operation
}
}spl_autoload_register (Array (' Myloader ', ' doautoload '));
?>

As you can see, the SPL AutoLoad Register is also able to include multiple load logic in the form of an array. You can also use SPL autoload unregister to remove load logic that is no longer needed, which is always used.
Iterators
Iterations are one of the common design patterns that are commonly used in a set of data for a unified traversal operation. It is no exaggeration to say that SPL provides all of the corresponding data types you need for iterators.
A very good example of this is traversing a directory. The general practice is to use Scandir, and then skip the "." and "..", as well as other files that do not meet the criteria. For example, you need to traverse a directory to extract the image files, you need to determine whether it is a JPG, GIF end.
The following code is an example of an iterator that uses SPL to perform the above recursive search for a picture file in the specified directory:

The code is as follows:
<?php
Class Recursivefilefilteriterator extends Filteriterator {
The extension that satisfies the condition
Protected $ext = array (' jpg ', ' gif ');
/**
* Provide $path and generate the corresponding directory iterator
*/
Public function __construct ($path) {
Parent::__construct (New Recursiveiteratoriterator (New Recursivedirectoryiterator ($path)));
}
/**
* Check if the file name extension meets the criteria
*/
Public Function accept () {
$item = $this->getinneriterator ();
if ($item->isfile () &&
In_array (PathInfo ($item->getfilename (), pathinfo_extension), $this->ext)) {
return TRUE;
}
}
}
Instantiation of
foreach (New Recursivefilefilteriterator ('/path/to/something ') as $item) {
Echo $item. Php_eol;
}
?>


You might say that this is not spending more code to do the same thing? So, looking at the code above, don't you have a highly reusable and testable code:)

Analysis : Think about it, if we put together the collection object and the operation of the collection object, when we want to iterate over the elements of the collection object in a different way, we need to modify the collection object, violate the "single responsibility Principle", and the iterator pattern will separate the data structure and data structure, and the two can develop independently.

Advantages:

1. Supports multiple traversal methods. For example, there is a sequence table, we can provide a positive sequence traversal, reverse-traverse two kinds of iterators as needed. The user only needs to get our iterators, and we can perform traversal operations on the collection.

2. The aggregation class is simplified. Because of the introduction of Iterators, the original collection objects do not have to traverse the collection elements themselves.

3. Adding new aggregation classes and iterator classes is convenient, two dimensions can be independent of each other

4. Provides a unified interface for different collection structures, enabling the same algorithm to operate on different sets of structures

Disadvantages:

1. Iterator mode adds a new collection object to the separation of responsibility for storing data and traversing data add the corresponding iterator class, increase the number of classes in pairs, and increase the complexity of the system to some extent

Usage scenarios:

1. Access an aggregated object content without exposing its internal display

2. Need to provide multiple traversal methods for aggregate objects

3. Provide a unified interface for traversing different aggregation structures

PHP SPL use method Auto load and iterator

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.