Banner of None

Creating A Real Website with PHP object oriented - part 4 - Autoload and Register Classes


Category: php

Date: August 2020
Views: 1.26K


Every php file you create must be included at some point before you use it. but as the website becomes bigger and the number of files increases, it becomes extremely difficult to keep track of the files. if you can't organize your code you might find yourself including the same file multiple times. and the code itself will look ugly and might not be resources friendly

In this tutorial we will introduce the concept of autoloading and registring classes only when needed. A class file will be included only when we are trying to instansiate it by creating an object from it. The include procedure will be neat and elegant. all because of the php function spl_autoload_register. IT was introduced since PHP 5.1 . it takes a function as a parameter, this function will hold the include statements we need. and returns true on success otherwise it returns false.

First we define our autoload function, it is in this part of our code that our class files naming convention will become helpful, as it will simplify the process of including the files. as we decided earlier all our class files will be either in "classes" or "views" directories. so the included file will look like :

"resources/classes/$classname.class.php"
"resources/views/$classname.class.php"

Autoloading And registring classes with spl_autoload_register



//index.php file:
spl_autoload_register('myautoloader');
function myautoloader($classname){
    $fname = "sources/classes/$classname.class.php";
    if(file_exists($fname)){
        include_once $fname;
        return true;
    }
    $fname = "sources/views/$classname.class.php";
    if(file_exists($fname)){
        include_once $fname;
        return true;
    }
    return false;
}


With this code; we will no longer worry about including any class file in any part of our project. we can even use any class in any other class and it will be loaded and registred as I illustrated in the following video:



1.26K views

Previous Article Next Article

0 Comments, latest

No comments.