PHP+SPL Application Case Detailed

Source: Internet
Author: User
Tags autoload spl zend framework
This time to everyone to bring PHP+SPL application case detailed, PHP+SPL application of attention to what, the following is the actual case, together to see.

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), from PHP 5.0 built-in components and interfaces, and from the PHP5.3 has gradually matured. 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 contains several objects such as Exceptions,splobserver,spltorage , and splautoloadregister, Help Functions (helper functions), such as Splclasses,iteratorapply , are used to overload 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

If you are a "textbook programmer", then you are guaranteed to know how to use autoload instead of includes/requires operations to load the corresponding classes 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 a project becomes more complex, the autoload logic within it becomes complex. In the end, you will even add the exception judgment and write all the logic loaded into the class.

We all know that "eggs cannot be placed in a basket", using SPL to separate autoload the load 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.

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

As you can see, spl_autoload_register it is possible to add multiple load logic in the form of arrays. At the same time, you can also use spl_autoload_unregister to remove the 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 scandir to use, and then skip "." 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:

<?phpclass Recursivefilefilteriterator extends Filteriterator {  //Meet the condition extension  protected $ext = array (' jpg ', ' GIF ');  /**   * Provides $path and generates a corresponding directory 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 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.

Splfixedarray

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.

Data

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 they are not specifically used to describe the data structure- A single misoperation 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.

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

PHP Implementation Huffman encoding/decoding steps

PHP Direct Insert Sort Case analysis

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.