Build Autoload PHP Classes

pomosda Zainul Abedin

This post will explain PHP autoload and name space concept using a few basic question and answer about PHP autoload along with some examples.

What is Autoloading in PHP?

PHP provides helper functions to include or import PHP files, if it has not been included before. if we use PHP autoload then we don't need to write require or include statement for each PHP class files. We should to use modern PHP way now.

Why we need auto loading?

It is a good question. why we need it, although we can write require or include statements whenever we need. As PHP has evolved using OOPs concept, we create more classes for our PHP project and create a separate PHP file for each single PHP class. Hence we increase the number of require or include statements. therefore we need some standard way to include each files rather specifying include statement by our self every time. that is why PHP has provided some useful methods to resolve this problem.

PHP Autoloading Methods

PHP uses two function, one is magic method __autoload and another is spl_autoload_register. each of these have their own benefit. they accept one parameter which turns into class name whenever we instantiate that class object. inside these method we could write our logic to load PHP class file.

What is difference between __autoload and sp_autload_resgister function?

__autoload method is magic method which means you can define it only once. therefore you would have only one logic to include PHP class files whereas spl_autoload_register is defined function which accept function name as parameter and we can define specified function with our logic. that mean we can have multiple implementation of inclusion of PHP files with help of spl_autoload_register.

<?php

/**
 * autoload method
 */
function __autoload($class)
{
  require $class.'.php';
}

//spl_autoload_register

/**
 * autoload method one
 */
function autoloadOne($class)
{
  require "/dir-one/".$class.".php";
}

/**
 * autoload method two
 */
function autoloadTwo($class)
{
  require "/dir-two/".$class.".php";
}

//register auto loader
spl_autoload_register("autoloadOne");
spl_autoload_register("autoloadTwo");

What is namespace?

PHP normally wont allow two class with same name. but later 5.3 introduce concept of namespace which create a ownership of class so that two different class can have same class name but with different ownership.

What is importance of namespace in autloading

when we autoload class we get a parameter into autload function. when you echo that parameter it will print that class name and namespace provides directory structure for classes.

<?php

namespace Module\User\Controller;
namespace Module\User\Entity;
namespace Module\User\Form;
namespace Module\User\Validator;

If we autoload above class then we will get whole namespace of that class along with class name e.g namespace_autoload.php

<?php
function __autoload($class)
{
  echo "class path = ".$class;
  die ;
}

new \Module\User\Controller();

// it will print
// class path = Module\User\Controller

with help of this information we can organize classes according to our project directory structure. let say you have following project structure

project
 |__Module
 |    |__User
 |         |__Controller
 |         |__Entity
 |         |__Form
 |
 |__autoload.php


then you can create PHP classes with namespace as

project
 |__Module
 |    |__User
 |         |__Controller // class : IndexController , namespace Module\User\Controller
 |         |__Entity     // class : User , namespace Module\User\Entity
 |         |__Form       // class : UserForm , namespace Module\User\Form
 |
 |__autoload.php


autoload.php

<?php

//include namespace

use Module\User\Controller\IndexController;
use Module\User\Entity\User;
use Module\User\Form\UserForm;

/**
 * Autload project files
 */
function __autoload($class)
{
  echo $class;
  require $class;
}

// instantiate classes
$controller = new IndexController();
//(it will print)  Module\User\Controller\IndexController and load this class

$user = new User();
//(it will print)  Module\User\Entity\User  and load this class

$userForm = new UserForm();
//(it will print) Module\User\Form\UserForm  and load this class

as you can see how namespace helps to organize project structure and autoload the classes.

What is difference between following two sets of statements

namespace autoloading                           Direct include files
============================================================================
use Module\User\Controller\IndexController;  	require "Module\User\Control...
use Module\User\Entity\User;       	            require "Module\User\Entity..	
use Module\User\Form\UserForm;                  require "Module\User\Form\..       		
============================================================================

General difference is require statement accept full directory path where in case of namespace we can set logic to autoload PHP files with different directory structure and can minimize the namespace length. Let see the example, suppose you have following directory for your project library files.

project
 |
 |__vendor
 |
 |__lib
   |
   |__src
     |
     |__components
       |
       |__HTTP  //Request, Response classes
       |
       |__Controller  //BaseController classes
       |
       |__Form //BaseForm classes

 ..... many more files


Using require statement need to write following code.

<?php

 require "/vendor/lib/src/components/HTTP/Request";
 require "/vendor/lib/src/components/HTTP/Response";
 require "/vendor/lib/src/components/Controller/BaseController";
 require "/vendor/lib/src/components/Form/BaseForm";

Which is very lengthy and not properly organized.

With help of autoload and namespace we can reduce and class path and organize structure in much proper ways.


<?php

define("LIB_PATH", "/vendor/lib/src/components");

use HTTP\Request;
use HTTP\Response;
use Controller\BaseController;
use Form\BaseForm;

/**
 *  autoload lib class files
 */
function __autoload($class)
{
  // set class path
  $class_path = LIB_PATH.$class;

  //include class file
  echo $class_path;
  require $class_path;
}

$request = new Request;
// (it will print)  /vendor/lib/src/components/HTTP/Request

$controller = new BaseController;
// (it will print)  /vendor/lib/src/components/Controller/BaseController

Summary

o autoload helps to load all PHP classes of a PHP project.
o namespace helps to organize your PHP classes
o combination of autoload and namespace organize and load PHP project in standardized way.

Source : zainabed.com
  • 02 Nov 2014
  • By Zainul Abedin
  • PHP-5
  • 1001 Read