Hyvor Developer

Autoloading Classes/Namespaces

Today we are going to discuss everything about classes and namespaces autoloading in PHP. However, before you start you must have a basic knowledge on PHP classes. If not, we prefer you to follow our tutorial on Object Oriented Programming with PHP (Comming Soon)

At the end, you will learn

What is Autoloading?

Most of the developers working with OOP(Object Oriented Programming) tends to save each class definition in a separate file. In this case, developers face a big problem. They have to include lots of files at the beginning of the document. Let's consider the following example.

Consider you are going to use several classes that are saved in separated files in your root directory.

  • dog.php
  • cat.php
  • cow.php
  • goat.php
  • fox.php

Then create index.html in your root directory and add following code


<?php

$dog = new dog();


Fatal Error: Class "dog" not found

You'll get the above error because any programming language doesn't find class files and include them by itself. So, you have to include all the class files before you call the class. (Usually it's included at the beginning of the document)

But, when including files developers face below shown problem. If they use 10 classes they have to include all the class files at the beginning.


<?php
include('dog.php');
include('cat.php');
include('cow.php');
include('goat.php');
include('fox.php');


When your project grows day-by-day it may need to include 100+ class files in a document. How can a developer do that in lot of documents without making a mistake? It's impossible! To solve this problem the autoload function comes!

Autoloading

Mainly there are two ways to define a autoload function.

  1. spl_autoload_register function (Highly recommended)
  2. __autoload function
spl_autoload_register is strongly recommended to use because of it's flexibility. The __autoload function is discouraged and will be deprecated soon. Let's see how to use it and how it works.

This will register autoload function and will try to load class files


<?php

spl_autoload_register(function($className) {
	include_once $className . '.php';
});

$dog = new dog();
$cat = new cat();

// static_methods below
echo cow::getToken();
echo fox::$name;


Step By Step...

  • First we define the autoload function with spl_autoload_register function.
    • When a new class called the callback function triggers.
    • Then, PHP sends the class's name as a parameter or the function and we have used it as $className
    • Then, we can use following functions to include the class file
      1. require
      2. require_once
      3. include
      4. include_once
    • All of those functions have their own pros and cons. The best one to use when autoloading is include_once
    • It won't stop the execution if an error occurs. Also, it won't include the same file twice. Therefore it's used widely by developers to include class files.
    • Did you notice something unusual in the code? Nevermind! In PHP include_once 'class.php' is same as include_once('class.php'). Use anything you like.
    • Finally we add the .php extension and include it.
  • Then when we call a class (like in the above example), the callback function is triggered. Then class file is included.

Think about the time the code new dog(); is executed. Then PHP calls the callback function. "dog" is sent as the parameter ($className). Then "dog.php" is included.

How To Organize Your Classes Like a PRO

How does an experienced programmer organize their class files? They use some simple tricks. Here is a simple and powerful file structure


/ 
	ajax
	inc
	class 
		class1.php
		class2.php
		class3.php
	css
	js 
	images


Simply, save all the class files in a folder in the root ("class" is recommended as the folder name).
Then create your powerful autoload function.


<?php

spl_autoload_register(function($className) {
	include_once $_SERVER['DOCUMENT_ROOT'] . '/class/' . $className . '.php';
});


Explained...

  • Here we create an autoload function as we discussed previously. (But this function has more advantages than the previous one)
  • $_SERVER['DOCUMENT_ROOT'] (string) holds the path of the root folder in the server computer. This variable is set by the server when the page is requested. However, by using this trick you can use class files with any document in any sub folder.
  • As an example, think that you are using class1 in the file /ajax/update.php. When you trigger the class, the class name is added to the $className variable in the spl_autoload_function. If we use previous function (mentioned in the first part of this tutorial) it will include a file relative to the current folder, /ajax/class/class1.php. By using $_SERVER['DOCUMENT_ROOT'] it will include something like /web/www/public_html/class/class1.php which is an absolute path.

Now, you can use your classes anywhere in your website with PHP! However, you have to use a different method when implementing an autoload function in a subdomain. Check out our tutorial on it.

Important! You must save the class files with the name of the class. Otherwise this trick won't work.

Autoloading Namespaces

Autoloading namespaces is an interesting topic. By the introduction of namespaces in PHP 5.3 PHP developers could encapsulate their items and it made handling scripts easy. However, we only discuss about how to autoload namespaces here. If you need to learn more about namespaces please visit our tutorial(Coming Soon) on it. Let's learn how to autoload namespaces. First of all we have to learn the use of namespaces.

When a website becomes larger, it's harder to keep all the class files in a same directory. Also we have to use very long names for files and classes, such as animal_dog_dog1_addName. It is a really bad practice. Namespaces are introduced to prevent this problem. Let's see how it works!

By using namespaces you can save your classes in sub folders. The file of the class name can be saved in /class/dog as well as /class/cat. Here is the file structure.


class
	animals
		dog.php
		cat.php
		goat.php
	birds
		owl.php
		peacock.php
	pets
		dog.php
		cat.php
	mainClass1.php
	mainClass2.php
	mainClass3.php


In above file structure you can understand, different files with the same name can be saved in different locations (folders). Namespaces are based on this simple logic. Now the problem is how to autoload them? Here is how namespaces are called with PHP.

	
<?php

spl_autoload_register(function($className) {
	include_once $_SERVER['DOCUMENT_ROOT'] . '/class/' . $className . '.php';
});

$dog = new animal\dog(); 
$cat = new animal\cat();


// static functions
animal\cat::name();
animal\cat::appearance();


Step By Step...

  • First we defines the autoload function as we discussed earlier.
  • "animal\dog" will be as the $className parameter to the autoload function.
  • So, it will include /your_document_root/class/animal\dog.php. (See the back slash)
  • This autoloading function will work fine on Windows OS. But the "\" will cause errors in other operating systems.
  • Therefore we have to upgrade our autoloading function.
	
<?php

spl_autoload_register(function($className) {

	$className = str_replace("\\", DIRECTORY_SEPARATOR, $className);
	include_once $_SERVER['DOCUMENT_ROOT'] . '/class/' . $className . '.php';

});	


Explained...

  • We have added str_replace function here
  • It matches "\" (back slash).
  • Then replaces it with the value of DIRECTORY_SEPARATOR constant. (This is a PRE-DEFINED-CONSTANT which hold a string, the directory separator according to the operating system)
  • This piece of code replaces \ to / if necessary.

At The End

Here are some tips.
  • Always name the class file with the name of the class.
  • Use namespaces when necessary. (When the class files need to be stored in separate folders)
  • Create a powerful autoload function as we discussed above, which supports normal classes as well as namespaces.
  • It is a bad practice to add spl_autoload_register in all the php scripts. So, create a file called autoload.php and save it in the root directory (or in a directory you have include files).
  • Then you just have to include autoload.php in a php script to register the autoload function. (include_once $_SERVER['DOCUMENT_ROOT'] . '/autoload.php')

If you have any questions comment below. We are always here to help you.

Thanks.

Author SupunKavinda