Adding wordpress autoload to plugin boilerplate

0
(0)

The wordpress plugin boilerplate generator is a great site for creating a starting point of a new wordpress plugin, but by default when you generate the code there is no autoload included so as you add new classes you also have to add their file into the loader class. This post shows how to add a wordpress autoload method so your new classes are loaded ‘on-the-fly’.

Adding WordPress autoload

The normal method which is responsible for loading the classes is the load_dependencies() method in the main plugin class and this is shown below from a module I’m creating called TaxonomyBrowser. As you can see the class files are loaded by individual require_once statements for each of the different class names.

private function load_dependencies() {

	/**
	 * The class responsible for orchestrating the actions and filters of the
	 * core plugin.
	 */
	require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-plugin-name-loader.php';

	/**
	 * The class responsible for defining internationalization functionality
	 * of the plugin.
	 */
	require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-plugin-name-i18n.php';

	/**
	 * The class responsible for defining all actions that occur in the admin area.
	 */
	require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-plugin-name-admin.php';

	/**
	 * The class responsible for defining all actions that occur in the public-facing
	 * side of the site.
	 */
	require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/class-plugin-name-public.php';
	$this->loader = new Plugin_Name_Loader();
}

To add wordpress autoload functionality I change the method to look like this:

private function load_dependencies() {
        // Setup a wordpress autoload function
        spl_autoload_register( array($this, 'taxonomybrowser_autoloader') );
    
        // Start the plugin main loader
        $this->loader = new Taxonomybrowser_Loader();
}

private function taxonomybrowser_autoloader($class_name) {
        // Convert the class name to the file name
        $class_file = 'class-' . str_replace( '_', '-', strtolower($class_name) ) . '.php';

        // Set up the list of directories to look in
        $classes_dir = array();
        $include_dir = realpath( plugin_dir_path( __FILE__ ) );
        $classes_dir[] = $include_dir;
        // Add each of the possible directories to the list
        foreach( array( 'admin', 'public') as $option) {
            $classes_dir[] = str_replace('includes', $option, $include_dir);
        }
        // Look in each directory and see if the class file exists
        foreach ($classes_dir as $class_dir) {
            $inc = $class_dir . DIRECTORY_SEPARATOR .  $class_file;
            // If it does require it
            if (file_exists($inc)) {
                require_once $inc;
                return true;
            }
        }
        return false;
}

So the first thing this does is register an autoload function as a local method and then removes all the individual require_once calls. The autoload function is shown in the code below the load_dependencies method.

The autoload function will be called with any class names which the system can’t find and it is responsible for making sure the correct class file is required.

The first part of the autoload converts the class name into the file name which holds the class. The code which goes here will depend on the convention you have adopted to name your class files. In this example, the convention is to put classes into a file called ‘class-xxxx.php’ where xxxx is the class name with underscores converted to hyphens. This is the convention which the wordpress boilerplate code generator uses.

With the filename sorted, we need to create the list of directories the class could be in. For this boilerplate framework, the directories are either ‘includes’, ‘admin’ or ‘public’. Since the file that this code lives in is in the includes directory we take advantage of that by finding the directory the file is in with

realpath( plugin_dir_path( __FILE__ ) );

and then use str_replace to change the ‘includes’ to admin and public to get all the possible directories.

Then it’s just a question of looping through each of the possible directories and finding if the requested class file exists – if it does we include it with a requires-once and return.

The advantage of making this change is that as new class files are added to the project, they are automatically found and included and don’t need to be manually added.

The only time you would need to make more changes is if you add new directories where class files are located – in that case you just add those directories into the autoloader and they will be automatically found.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Please consider sharing on social media!

Leave a Reply

Your email address will not be published. Required fields are marked *

wordpress 2171594 1280 e1550066032962 Previous post Installing WordPress – Apache web server configuration
install start screen Next post WordPress install process and DNS