PHP SPL Forgotten Gem _php Tutorial

Source: Internet
Author: User
Tags autoload spl zend framework
Rafael Dohms above the article let me surprise, can not help but translated down, at the same time supplemented part of the content.

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 SPLautoloadRegister, SPLclasses, iteratorapply 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.


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.


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:

  Getinneriterator ();        if ($item->isfile () &&                 In_array (PathInfo ($item->getfilename (), pathinfo_extension), $this- EXT) {            return TRUE;}        }    } Instantiate the 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:)

The following are the other iterators provided by SPL:

  • Recursiveiterator
  • Recursiveiteratoriterator
  • Outeriterator
  • Iteratoriterator
  • Filteriterator
  • Recursivefilteriterator
  • Parentiterator
  • Seekableiterator
  • Limititerator
  • Globiterator
  • Cachingiterator
  • Recursivecachingiterator
  • Norewinditerator
  • Appenditerator
  • Recursiveiteratoriterator
  • Infiniteiterator
  • Regexiterator
  • Recursiveregexiterator
  • Emptyiterator
  • Recursivetreeiterator
  • Arrayiterator

    Since PHP5.3, there are many more iterators built in, and I think you can try it, maybe it will change your habit of writing traditional code.


    SPL also includes a series of array manipulation tools, such as the ability to instantiate a fixed-length array using Splfixedarray. So why use it? Because it's faster, and it's even related to your wage problem:)

    We know that the regular array of PHP contains different types of keys, such as numbers, strings, etc., and the length is variable. It is because of these "advanced features",php to hash (hash) to get the corresponding value through the key-in fact, this can cause performance problems in certain situations. "

    Splfixedarray is not using hash storage because it uses a fixed number key. Not exactly, even you can think of it as a C-array. This is why Splfixedarray is faster than the usual array (only in PHP5.3).

    How fast is that, the following group of data can give you a glimpse of what it is.

    If you need a lot of array operation, then you can try it and believe it is trustworthy.


    SPL also provides some basic types of data structure implementations. Although we can use traditional variable types to describe data structures, such as using arrays to describe stacks (Strack)-and then use the corresponding way pop and push (arraypop (), arraypush ()), but you have to be careful, • Because, after all, they are not specifically designed to describe data structures-a single error operation can destroy the stack.

    The Splstack object of SPL describes the data strictly in the form of stacks and provides corresponding methods. At the same time, such code should also be able to understand it in the Operation Stack rather than an array, so that your partner can better understand the corresponding code, and it is faster.

    Finally, perhaps these pale examples are not enough to "tempt you" to use SPL. By practicing the truth, SPL has more and more powerful features that you need to dig yourself. And it is like a gem of slowly sculpted, in order to emit brilliance. true techarticle Rafael dohms above the article let me surprise, can not help but translated down, at the same time supplemented part of the content. spl,php standard library (PHP library), from PHP 5.0 ...

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