Hello World Master

Tutorials, articles and quizzes on Software Development

PHP > Articles

Including composer in a WordPress plugin and implementing autoload

This article is associated with the following tutorial series

Building a basic plugin in WordPress

To allow our plugin to be more developer friendly, we want to include composer to be able to split our code in multiple files and import already existing modules in our PHP plugin.

You will need to install composer and be able to run it on your command line to move forward

Adding the composer.json in your plugin

To use composer with our plugin, we want to add a composer.json file to the root of our plugin. To do this, we want to open up a terminal, go to our plugin’s root and then run composer init

There you will get a following command line setup screen

Package name (<vendor>/<name>) [developer/my-first-plugin]: 
Description []: 
Author [Victoryflame <realvictoryflame@gmail.com>, n to skip]: 
Minimum Stability []: 
Package Type (e.g. library, project, metapackage, composer-plugin) []: 
License []: GPL

Define your dependencies.

Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no

{
    "name": "developer/my-first-plugin",
    "license": "GPL",
    "authors": [
        {
            "name": "Victoryflame",
            "email": "realvictoryflame@gmail.com"
        }
    ],
    "require": {}
}

Do you confirm generation [yes]? yes

Implementing autoload in composer.json

Implementing autoload will allow us to import PHP classes from separate files. Lets add a new key/value pair in our composer.json configuration

"autoload": {
  "psr-4": {"Inc\\": "./inc"}
}

This means that the namespace Inc will be in the inc folder.

Before we run composer install, lets add our PHP classes in their own files

Moving PHP classes into their own files

First lets create a file inside the inc files called Sidemenu.php

<?php

  namespace Inc;

  use Inc\View;

  class Sidemenu {
    public static function addSideMenuItems() {
  
      $view = new View();
  
      $pages = array(
        array(
          'page_title' => 'Victoryflame Plugin', 
          'menu_title' => 'Victoryflame', 
          'capability' => 'manage_options', 
          'menu_slug' => 'victoryflame_plugin', 
          'callback' => array( $view, 'VictoryflameView'), // view->VictoryflameView
          'icon_url' => 'dashicons-store',
        )
      );
  
      $page = $pages[0];
      add_menu_page( $page['page_title'], $page['menu_title'], $page['capability'], $page['menu_slug'], $page['callback'], $page['icon_url'] );
    }
  }

Next, lets move our View class out into its own file

<?php

  namespace Inc;

  class View {

    public function VictoryflameView() {
      echo '<h1> I am the page your menu directed you to</h1>';
    }

  }

Refactor existing code to use autoload to import classes

In our my-first-plugin.php file, remove the classes that we moved over to our new files should be removed from it and we need to add the following just before our registerMenuPage function


if ( file_exists( dirname( __FILE__ ) . '/vendor/autoload.php' ) ) {
	require_once dirname( __FILE__ ) . '/vendor/autoload.php';
}

This allows us to use our other PHP classes that are now inside different folders.

Next we want to modify the registerMenuPage function so we use our imported class. The below code refactors our function to do so

function registerMenuPage() {
  Inc\Sidemenu::addSideMenuItems();
}

Finally, we need to update the code that checks to see if our class exists, because we now have it in a different location

if ( class_exists( 'Inc\\Sidemenu' ) ) {
  add_action( 'admin_menu', 'registerMenuPage' );
}