This is how I am calling controllers wherever they are needed.
$file = 'App/Controller/' . $controller . '.php';
if (is_file($file)) {
include_once($file);
$namespace = 'App\Controller\\';
$relative_controller = $namespace . $controller;
$relative_controller = new $relative_controller();
if (is_callable(array($relative_controller, 'index'))) {
return call_user_func(array($relative_controller, 'index'));
} else {
echo 'Function not callable';
}
} else {
echo 'file missing';
}
All my controllers/classes have namespace defined as you can see in the above code on line 4 where it says $namespace = 'App\Controller\\' and I only had to pass the name of the controller (HomeController, AboutController, UserController) to call them, it works good.
Off late it is becoming cumbersome having all the controllers (more and more controllers keeps popping out) under one directory, so I decided to move them to subdirectories like
App/Controller/Information
App/Controller/User
but if I start moving these controllers to their corresponding directories the namespace changes as well. Now every controller will have their subdirectory name in their namespace (as opposed to all having the same namespace 'App\Controller').
How do I now dynamically include the namespace in the loader (above code) where previously it was just one namespace doing all the work?
If I move the about us, contact us, policy controller under 'App/Controller/Information' the namespace changes from App\Controller to App\Controller\Information.
$controllerto'Information/whatever'as well instead of just'whatever'. If not, then you need a map that resolves every "short" controller name to its "long" controller name.