PHP

Autoloading classes, interfaces or traits

Classes should be defined before they are used, but you can make use of autoloading to load classes when they are required. When we use the statement new ClassName(), if the class ClassName doesn’t exist (because it hasn’t been included), PHP trigger an autoloader that can then load the file ClassName.php, and the rest of the script will continue as normal without us ever needing to manually write the line require 'ClassName.php';.

What is autoloading

Autoloading is the process of automatically loading PHP classes without explicitly loading them with the require(), require_once(), include(), or include_once() functions.

It’s necessary to name your class files exactly the same as your classes. The class Views would be placed in Views.php, a class called Users would be stored in Users.php and so on.

What is autoloader

An autoloader is a function that takes a class name as an argument and then includes the file that contains the corresponding class, for example:

function autoloader ( $class ) {
 $path = $DOCUMENT_ROOT . '/classes/';
 require $path . $class .'.php'; 
}

__autoload() function (deprecated)

__autoload(), a magic function, is automatically invoked by the PHP when we instantiate a class that has not already been loaded. For example:

function __autoload($class) {
 $path = $DOCUMENT_ROOT . '/classes/';
 require_once  $path . $class .'.php';
}
$myCls = new myClass();

As of PHP 7.2.0 the __autoload()function has been deprecated. Now it is recommended to use the spl_autoload_register for that purpose instead.

spl_autoload_register()

PHP 5.1.2 introduced the more flexible spl_autoload_register() function in its SPL library which allows you to register multiple autoloader functions.

What is SPL library?

The Standard PHP Library (SPL) is a built-in library to solve common problems. It provides:

  • Datastructures, such as: linked lists, stack, queue, heap, fixed array, object storage etc.
  • Iterators, such as: array iterator, directory iterator, fs iterator, regex iterator etc.
  • Interfaces, such as: countable, OuterIterator etc.
  • Exceptions
  • Spl functions, such as: spl_autoload_extensions, spl_autoload_functions, spl_autoload_register, spl_autoload_unregister, spl_autoload etc.
  • File handling functions

For more information visit: http://php.net/manual/en/intro.spl.php

Registering multiple autoloader functions

The spl_autoload_register() allows to create an autoload chain, a series of functions that can be called to try and load a class or interface:

<?php
function loadModel($class) {
 $path = $DOCUMENT_ROOT . '/models/';
 require_once $path . $class .'.php';
}

function loadView($class) {
 $path = $DOCUMENT_ROOT . '/views/';
 require_once $path . $class .'.php';}
}

spl_autoload_register('loadModel');
spl_autoload_register('loadView');

Why to use an autoloader

How often have you seen code like this at the top of your PHP files?

<?php
 require 'file_1.php';
 require 'file_2.php';
 require 'file_3.php';

All too often, right? The require(), require_once(), include(), and include_once() functions load an external PHP file into the current script, and they work wonderfully if you have only a few PHP scripts.

However, what if you need to include a hundred PHP scripts? The require() and include() functions do not scale well, and this is why PHP autoloaders are important. An autoloader is a strategy for finding a PHP class, interface, or trait and loading it into the PHP interpreter on-demand at run-time, without explicitly including files.

Autoloading Classes Example

  1. Create directories / folders on your document root: classes, views and models.
  2. Create two PHP files in each folder: home.php and all.php.
  3. Create classes by writing the following code in each file:
    classes/home.php

    <?php
    namespace classes;
    class home {
     public function get(){
      return 'classes/home.php';
     }
    }

    classes/all.php

    <?php
    namespace classes;
    class all {
     public function get(){
      return 'classes/all.php';
     }
    }

    models/home.php

    <?php
    namespace models;
    class home {
     public function get(){
      return 'models/home.php';
     }
    }

    models/all.php

    <?php
    namespace models;
    class all {
     public function get(){
      return 'models/all.php';
     }
    }

    views/home.php

    <?php
    namespace views;
    class home {
     public function get(){
      return 'views/home.php';
     }
    }

    classes/all.php

    <?php
    namespace views;
    class all {
     public function get(){
      return 'views/all.php';
     }
    }
  4. Create a file loader.php at document root and write the following code:
    <?php
    
    spl_autoload_register();
    $home = new classes\home();
    echo $home->get() . <br>;
    
    $home = new views\home();
    echo $home->get(). <br>;
    
    $home = new models\home();
    echo $home->get(). <br>;
    
    $all = new classes\all();
    echo $all->get(). <br>;
    
    $all = new views\all();
    echo $all->get(). <br>;
    
    $all = new models\all();
    echo $all->get();
    
    /*Output
    classes/home.php
    views/home.php
    models/home.php
    classes/all.php
    views/all.php
    models/all.php*/
    

You can see all classes loaded without using the include or require keywords. Since PHP 5.3, you can use spl_autoload_register() with namespaces, which means that you can organize your project and autoload your php classes without any require or include.

Advertisement:
Advertisement: