0

I'm starting a new app and have finally decided to join the new age using Namespaces. I'm finding myself constantly writing code like this:

 $dynamicControllerName = "MyController";
 $controllerName = "System\\App\\Controllers\\" . $dynamicControllerName;
 $controller = new $controller;

Anytime I try to use the use keyword it doesn't seem work (or I don't understand it correctly):

 use System\App\Controllers as Controller

And then

 $dynamicControllerName = "MyController";
 $controllerName = "Controller\\" . $dynamicControllerName;
 $controller = new $controller;

That makes my autoloader think the path is my base path plus "/Controller/MyController" rather than the desired "/System/App/Controllers/MyController". I've tried varying combinations of with and without the prefix slashes.

A real world example of what I'm attempting looks like this (trying to get MyController):

 namespace System\App\Lib;

 use System\App\Controllers as Controller;

 class Router
 {
    public function dispatch(Request $request)
    {
        //...some dispatch code here

        // Instantiate Controller (THIS DOESNT WORK)
        $controllerName = "Controller\\" . $request->controller;
        $controller = new $controllerName($param1, $param2);

        //...some dispatch code here
    }
 }

I would think the above would request a class from my autoloader called System\App\Controllers\MyController and then I can flip the slashes and add a file extension and voila. Instead it comes through as Controller\MyController which doesn't exist. Is it because the Router class is in a different namespace? What am I missing?

TL;DR; In an MVC pattern, how can I dynamically instantiate a class instance without having to type the fully qualified namespace every time?

P.S. I'm using PHP 5.4.15

EDIT

Autoloading is setup with:

// Define AutoLoading
spl_autoload_register(array('System\App', 'autoload'));

The autoload function:

/**
* Autoloading via PSR-0 Namespacing
*/
protected static function autoload($className = false)
{
    var_dump($className);
    if($className)
    {
        $className = ltrim($className, '\\');
        $fileName  = '';
        $namespace = '';
        if ($lastNsPos = strripos($className, '\\')) {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }
        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
        $fileName = App::$SYS_PATH . DIRECTORY_SEPARATOR . $fileName;
        include_once $fileName;
    }
}

When I do dumps of the $className I can see whether PHP is recognizing a namespace or not.

tereško
  • 58,060
  • 25
  • 98
  • 150
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133

0 Answers0