Here is a partial structure of my project
root
|-App
|--Controller
|--Common
|-HomeController.php
|-HeaderController.php
|-FooterController.php
|-SidebarController.php
|--Info
|-AboutController.php
|-ContactController.php
I have my controllers placed in their corresponding directories for better management.
I recently added namespaces to them.
HomeController.php = namespace app\controller\common;
HeaderController.php = namespace app\controller\common;
AboutController.php = namespace app\controller\info;
ContactController.php = namespace app\controller\info;
To load these controllers, I am checking this autoloader below
spl_autoload_register(function ($class) {
$prefix = 'app\controller\common\\';
$base_dir = __DIR__ . '/app/controller/common/'; // your classes folder
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
return;
}
$relative_class = substr($class, $len);
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
if (file_exists($file)) {
require $file;
}
});
$home = new app\controller\common\HomeController();
$home->index();
and it works i.e. it autoload all controllers in the folder app > controller > common.
The problem is I do not understand how to load all other controllers which are in different folders (like the ones in the Info folder) and with different sub-namespace (namespace app\controller\info, namespace app\controller\client)?
The autoload has the namespace prefixed defined to $prefix = 'app\controller\common\\';
and I guess this is what I need to fix to accommodate all other controllers that there is to load them.
How do I fix this $prefix?