Reputation: 893
Ok im trying to get my head around autoload and i am a bit confused, i read a bunch of posts and now i think i am more confused, if i had a simple example i think i could get my head around it.
So lets say i have this simple project:
var/www/myproject/index.php
Then i have var/www/myproject/classes/database.php with this:
class Database {
function __construct() {
echo 'This is my Database Class <br />';
}
}
And also var/www/myproject/classes/functions.php with this:
class Functions {
function __construct() {
echo 'This is my functions class <br />';
}
}
And also var/www/myproject/classes/users.php with this:
class Users {
function __construct() {
echo 'This is my user class <br />';
}
}
Then lets assume i have 2 includes here:
var/www/myproject/includes/header.php
var/www/myproject/includes/footer.php
So how would i autoload all those files and classes. Im thinking something like this but the examples i come across seem very specific to their setup or only apply to one folder, or include namespace which i haven't grasped.
I was thinking my index might look something like this:
function __autoload($class_name) {
require_once 'classes/'.$class_name . '.php';
}
But then that wouldn't work for includes for header and footer so maybe something like this is more appropriate
$path = array('classes/','includes/');
foreach ($path as $directory) {
if (file_exists($directory . ? . '.php')) {
require_once ($directory . ? . '.php');
}
The idea being that it would include everything in the directory it finds but i am not sure how to do it, the ? was supposed to represent a wildcard and i understand this wont work, im trying to give an example of what im trying to do.
This must be something people come across a lot and im sure there is a good solution, just cant find an article that explains it well enough for me to understand
Upvotes: 0
Views: 978
Reputation: 338
If you use in your project namespaces i would recommend to use simple code:
class ClassLoader {
public function handle($class) {
$file = str_replace('\\', '/', $class.'.php');
if(!file_exists($file)){
throw new \Exception('class '.$class.' file not exists');
}
include_once $file;
}
}
$autloader = new Classes\ClassLoader;
spl_autoload_register(array($autloader, 'handle'));
// from now you can load all Classes from directories specified in namespace of class for example
/////////////////////////////////////////////
// directory => framework/classes/User.php //
/////////////////////////////////////////////
namespace framework\classes;
class User {
public function helloWorld(){
echo 'hello World';
}
}
////////////////////////
// and here index.php //
////////////////////////
$autloader = new Classes\ClassLoader;
spl_autoload_register(array($autloader, 'handle'));
$user = new \framework\classes\User();
$user->helloWorld();
Upvotes: 1