Single functions.php or split into many small files?

1. Does this have effect on WP performance in a visible way ?

IF it would have a real affect for some small files, then it would have an affect that has an impact lower than WP: PHP and server performance. Does it really have an affect? Not really. But you can still simply start doing performance tests yourself.

2. Is it better to keep it all within 1 file (functions.php)

Now the question is “What is better”? From overall file(s) loading time? From file organisation point of view? Anyway, it doesn’t make any difference. Do it in a way so you don’t loose overview and can maintain the result in a way that is pleasant for you.

3. what is the best way to go about this?

What I normally do is simply hooking somewhere in (plugins_loaded, after_setup_theme, etc. – depends on what you need) and then just require them all:

foreach ( glob( plugin_dir_path( __FILE__ ) ) as $file )
    require_once $file;

Anyway, you can make it a little more complicated and flexible as well. Take a look at that example:

<?php

namespace WCM;

defined( 'ABSPATH' ) OR exit;

class FilesLoader implements \IteratorAggregate
{
    private $path="";

    private $files = array();

    public function __construct( $path )
    {
        $this->setPath( $path );
        $this->setFiles();
    }

    public function setPath( $path )
    {
        if ( empty( $this->path ) )
            $this->path = \plugin_dir_path( __FILE__ ).$path;
    }

    public function setFiles()
    {
        return $this->files = glob( "{$this->getPath()}/*.php" );
    }

    public function getPath()
    {
        return $this->path;
    }

    public function getFiles()
    {
        return $this->files;
    }

    public function getIterator()
    {
        $iterator = new \ArrayIterator( $this->getFiles() );
        return $iterator;
    }

    public function loadFile( $file )
    {
        include_once $file;
    }
}

It’s a class that does basically the same (needs PHP 5.3+). The benefit is that it’s a bit more fine grained, so you can easily just load files from folders that you need to perform a specific task:

$fileLoader = new WCM\FilesLoader( 'assets/php' );

foreach ( $fileLoader as $file )
    $fileLoader->loadFile( $file );

Update

As we live in a new, post PHP v5.2 world, we can make use of the \FilterIterator. Example of the shortest variant:

$files = new \FilesystemIterator( __DIR__.'/src', \FilesystemIterator::SKIP_DOTS );
foreach ( $files as $file )
{
    /** @noinspection PhpIncludeInspection */
    ! $files->isDir() and include $files->getRealPath();
}

If you have to stick with PHP v5.2, then you still can go with the \DirectoryIterator and pretty much the same code.

Leave a Comment