How to recursively load PHP files in a Directory

Sam Ngu
2 min readJul 6, 2021

--

You’ve got a lot of files and nested files in a directory. However loading them 1 by 1 using require is simply too painful. Life is already tough, so please don’t do that to yourself.

In this tutorial, I will show you a few ways to achieve this.

Nah, we have better things to do in life than this.

Option 1: Using the infamous PHP iterator classes

PHP is kind enough to offer us the iterator classes to work with iterables. However, the APIs are quite low level. Let’s take a look at the code:

What is an iterator anyway?

An iterator is an object to loop through a series of items. You can think of iterator as the OOP way of looping.

We used 2 iterator classes here. The recursive directory iterator and recursive iterator iterator.

Recursive Directory Iterator

This iterator helps us to recursively iterate through a directory. The constructor accepts the folder path that we want to iterate through.

Recursive Iterator Iterator

A wrapper over an iterator instance to provide additional helper methods on the underlying iterator, for example, the valid() method. In the code above we are wrapping the recursive directory iterator .

Once we instantiated both iterators, we can start looping through the directory via a while loop, calling the next() method at the end to move on to the next item in the iterator.

If using the iterator classes is to complicated for you, I’ve created a PHP package doing just that! Feel free to check it out here.

Option 2: Using Symfony Finder

This is perhaps the easiest way recursively load all the files. Symfony offers the great Finder library that helps us to easily work with files and folders.

The following code will loop through all the files in $folderPath .

$folderPath = __DIR__ . '/somewhere/';
$finder = Finder::create()->in($folderPath)->files();
foreach ($finder as $file) { // $file is a SplFileInfo instance
// ...
require $file->getPathname(); // load the file
}

In each iteration, we will use the require keyword to load the file.

That’s it! Hope this tutorial helps.

--

--

No responses yet