Creating A Real Website with PHP object oriented - part 4 - Autoload and Register Classes
Category: php
Date: August 2020
Views: 1.61K
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/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:
Related Articles
- Maths
- 1APIC
- 3APIC
- Tronc Commun Sciences
- Tronc Commun Lettres
- 1 BAC Science
- 1 BAC Science Maths
- 1 Bac Lettre
- 2 Bac Science
- 2 Bac Science Maths
- Discussions
- Physics
- 1 BAC Science
- SVT
- 3 Année Collège
- Tronc Commun Sciences
- 1 BAC Science
- 1 BAC Science Maths
- 1 Bac Lettre
- 2 Bac Science
- Latex
- Templates
- Figures
Most Recent Articles
Most Viewed Articles
0 Comments, latest
No comments.