0

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.

3
  • Does this answer your question? PHP dynamic namespaces Commented Jan 25, 2020 at 12:59
  • The file path should match the namespace and the namespace should match the file path, it's that simple. You're now essentially renaming all your controllers, so you need to take that into account in your name resolution, e.g. you need to rename $controller to '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. Commented Jan 25, 2020 at 13:25
  • "Routing" enough said isn't it? Commented Jan 26, 2020 at 9:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.