Design patterns in action: Builder and Symfony Finder

The Symfony Finder ( Symfony\Component\Finder ) is a component that, according to its documentation, can be used to “build rules to find files and directories”. This functionality includes a numder of optional parameters that can be used to construct the Finder object based on what files or directories we are looking for. The Finder uses the Builder pattern in order to help the developer to parameterize the object to be constructed. I will quote just two methods of the Finder class that illustrate some typical features of the Builder pattern.

The method that is used to ask for the construction of a Finder object:

/**
 * Creates a new Finder.
 *
 * @return static
 */
public static function create()
{
    return new static();
}

You can see that there are not any required parameters that need to be passed for the construction.

One of the methods that parameterize the Finder object:

/**
 * Restricts the matching to directories only.
 *
 * @return $this
 */
public function directories()
{
    $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;

    return $this;
}

Let’s see the Finder component in action. As you may know, or not, Laravel PHP framework is not using the native PHP sessions but instead it is implementing its own session mechanism. In the FileSessionHandlerfile file ( Illuminate\Session\FileSessionHandlerfile ), which implements a file handler for session data, there the following method that handles the garbage collection of session files:

public function gc($lifetime)
{
    $files = Finder::create()
                ->in($this->path)
                ->files()
                ->ignoreDotFiles(true)
                ->date('<= now - '.$lifetime.' seconds');

    foreach ($files as $file) {
        $this->files->delete($file->getRealPath());
    }
}

The method is using the Symfony’s Finder in order to select the session files that need to be deleted and iterate through them.