Skip to main content

PHP Tutorials : Autoload PHP Classes

This tutorials post will explain PHP autoloader and namespace concept using few basic question and answer regarding PHP autoload functionality 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.

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.
e.g
<?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.
e.g
<?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 autloading Direct include files

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

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


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


Comments

Popular posts from this blog

AngularJs Tutorial: Getting Started

This tutorial will help you to create a dynamic web application using power of AngularJs. ·   What is AngularJs AngularJs is javascript MVC framework (maintained by Google) which molds static HTML application to dynamic web application. That was a brief introduction, you can find more information on Wiki and AngularJS Site . AngularJs follows MVC pattern to separate out model from view and manage it by controller. See this image Goal of using AngularJs is to convert static HTML template to dynamic (Angular) template.   ·   How to convert static template to dynamic (Angular) Template Now consider the following static HTML template which contain list of movies title. <html> <head></head> <body>   <h1>Upcoming Movies</h1> <ul>     <li>       <span>Godzilla</span>     </li> <li>       <span>Batman vs Superman</span>     </li> <li>       <span>Sta

Abstract Factory design pattern analysis

What is Abstract Factory design pattern?     The intent or definition of Abstract Factory is “ Provide an interface for creating families of related or dependent objects without specifying their concrete classes ” It is kind of an obscure definition, in order to understand it we need to break it into meaningful pieces. 1.  " Provide an interface "  When we talk about Abstract Factory we talk about interface not abstract class , Basically this design pattern gives us an Interface, like Interface in Java, C# , Typescript (abstract class).    Why interface?  Whenever we talk about any design pattern, it emphasizes more on how we are going to use it rather than implement it. Interface is always the right type to prefer because concrete class creates tight coupling whereas an interface isolates it from the rest of the system. At runtime we can get different solution, without updating our code. For example interface SecurityFactory

AngularJs Tutorials : Bootstrap

Every application starts with bootstrap process which initialize application and wire it other with dependencies and configurations. AngularJs is not different from other application. It also starts application with bootstrap process. Following operation happens inside AngularJs bootstrap process. Load application module. Create dependency injector and load dependencies. Compile HTML and create scope for application. All these steps happens inside angular.js scripting file. therefore we need to include it first. we can include it inside HEAD tag or at end of BODY tag. Note: Adding angular.js file at end of body tag will allow browser to load of HTML elements without any delay and afterwards load angular.js and begin bootstrapping process. You can get angular.js source file from https://code.angularjs.org/ <script src= ”https://code.angularjs.org/1.3.0/angular.js” type= ”text/javascript” > AngularJs bootstrap process happens on docum