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

php, web design, web development, angular, javascript, javascript developer, frontend web developer, html coding, css3, css, css3 animation, html5, reactjs, software developer, full stack developer, user interface designer, web developers life, web developers, coding life, coding days, python developer, website design, php object,

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:

Buy me A Coffee

Comments:

: We will never share your email