Autoloading

Updated on 28 Dec 2018

Introduction

Autoloading is the next new cool thing to come from PHP. Essentially instead of having to use require_once to include all your classes (that were created in separate files) you can autoload them instead.

For this tutorial we will be using composer and psr-4 standards.

Develop a class

Classes that use the psr-4 standard for autoloading require the use of a namespace.

I’m going to save this file as packageDir/Animal.php. The important thing here is that the file name matches the class name; this is a requirement.

namespace bkpackages;

class Animal {

    /**
     * @var string animal name
     */
    protected $name = '';

    /**
     * empty constructor
     */
    public function __construct() 
    {}

    /**
     * Returns the animal name
     * 
     * The animal name can be set with **setName**
     * 
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * set the Animal name
     * 
     * @param string $name the name to set the Animal too.
     * @throws Exception 
     */
    public function setName($name)
    {
        if(strlen($name) < 3)
            throw new Exception('The name is too short');

        $this->name = $name;
    }
}

Create a composer file

Next step is to create a composer file. It will have the following format.

{    
    "autoload": {
        "psr-4": {
          "package_name\\":"package_dir/"
        }
      }
}
  • package_name must be followed by \ and
  • package_dir is followed by /.

You can create sub-packages and sub-directories as well, however they still must follow the rules above.

Here is the file that I have used for my example.

{
    "autoload": {
        "psr-4": {
          "bkpackages\\":"packageDir/"
        }
      }
}

Rebuild composer autoloader

When you add in packages for autoload, we need to update the composer autoloader.

composer dump-autoload -o

Autoloading Classes - Technique I

Loading fully qualified namespaced classes.

require "vendor/autoload.php";

$animal = new bkpackages\Animal();

$animal->setName("Cat");
echo $animal->getName();

Autoloading Classes - Technique II

Including the namespace into your code.

require "vendor/autoload.php";
use bkpackages\Animal;

$animal = new Animal();

$animal->setName("Cat");
echo $animal->getName();