What exactly are the benefits of using a PHP 5 DirectoryIterator over PHP 4 “opendir/readdir/closedir”?

前端 未结 4 1336
迷失自我
迷失自我 2021-02-04 09:03

What exactly are the benefits of using a PHP 5 DirectoryIterator

$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) 
{
    // handle wh         


        
4条回答
  •  萌比男神i
    2021-02-04 09:57

    Benefit 1: You can hide away all the boring details.

    When using iterators you generally define them somewhere else, so real-life code would look something more like:

    // ImageFinder is an abstraction over an Iterator
    $images = new ImageFinder($base_directory);
    foreach ($images as $image) {
        // application logic goes here.
    }
    

    The specifics of iterating through directories, sub-directories and filtering out unwanted items are all hidden from the application. That's probably not the interesting part of your application anyway, so it's nice to be able to hide those bits away somewhere else.

    Benefit 2: What you do with the result is separated from obtaining the result.

    In the above example, you could swap out that specific iterator for another iterator and you don't have to change what you do with the result at all. This makes the code a bit easier to maintain and add new features to later on.

提交回复
热议问题