PHP SPL The gems they left behind

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

Rafael dohms the above article Let me be amazed, 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 the entire PHP5 development environment, without any setting at the same time.

It seems that many PHP developers are not using it, or even unheard of. The reason for this is that it can be traced to its spring snow-like documentation, which allows you to ignore "its existence".

This gem of SPL is sunk into the seabed like the "Heart of the Ocean" of the Titanic. And now it should be picked up by us. and put it where it should be, 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 contains several objects such as Exceptions, Splobserver, Spltorage, and SPL. Help functions (helper functions) for autoloadRegister, SPLclasses, iteratorapply, and so on, for overloading the corresponding functions.

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

Assuming you're a textbook-like program Ape, you're guaranteed to know how to use __autoload to replace the includes/requires operation to load the corresponding class lazily, right?

But for a long time, you will find that you are already in trouble, first of all you have to ensure that your class files must be in the specified file path, such as in the Zend framework you must use "_" to cut 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 complex. In the end, you will even increase the exception inference. and write all of the logic of the load class into it.

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 the corresponding method. Suppose it does not find the corresponding class. Then use the function you defined earlier.

<?phpclass Myloader {public    static function Doautoload ($class) {        //The corresponding autoload operation of this module    }}spl_autoload_ Register (Array (' Myloader ', ' doautoload '));? >

As you can see, the SPL autoload Register also adds multiple load logic in the form of arrays.

At the same time, you can also use SPL autoload unregister to remove load logic that is no longer needed. This function 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 appropriate data types you need for the iterator.

A good example of this is traversing a folder. The general practice is to use Scandir. Then skip "." and "..". and other files that do not meet the criteria.

For example, you need to traverse a folder to extract the image files, you need to infer whether it is a JPG, GIF end.

The following code is a sample of an iterator that uses SPL to run the above recursive search for a picture file in a specified folder:

<?phpclass Recursivefilefilteriterator extends Filteriterator {    //Meet the condition extension    protected $ext = array (' jpg ', ' GIF ');    /**     * Provides $path and generates the appropriate folder iterator */     public    function __construct ($path) {        parent::__construct (new Recursiveiteratoriterator (New Recursivedirectoryiterator ($path)));    }    /**     * Check if the file extension meets the criteria     *    /Public Function accept () {        $item = $this->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 a lot of other code to do the same thing? So, looking at the code above, don't you have a highly reusable and able to test 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 began. There are many other iterators built in, and I think you can try it. Maybe it will change your habit of writing traditional code.

Splfixedarray

SPL also includes a series of array manipulation tools. For example, you can instantiate a fixed-length array with Splfixedarray. So why use it? Because it's faster. And it's even related to your wage problem:)

We know that PHP's regular arrays include 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 by key-in fact this can cause performance problems in specific situations. "

And Splfixedarray is using a fixed number key. So it doesn't use hash storage. Not exactly, you can even 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.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvcghwzmvuz2h1bw==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

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

Data

At the same time, SPL also provides some basic types of data structure implementations. Although we can use the traditional variable types to describe the narrative data structure. For example, use an array to describe the narrative stack (Strack)-and then use the corresponding way pop and push (arraypop (), arraypush ()). But you have to be careful. • Since they are not specifically designed to describe the data structure, a single misoperation can destroy the stack.

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

Finally, perhaps the above examples of dire white are not enough to "tempt you" to use SPL.

In practice, many of the other, more powerful features of SPL require you to dig from us. It's slowly gemstone-like paint off. Exudes a splendid ability.

Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

PHP SPL The gems they left behind

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.