0

I'm modifying my dispatcher to take advantage of namespaces.

My autoloader is very standard and looks like this:

$paths = array(
get_include_path(),
ROOT . DS . 'library'  . DS . 'intranet'  . DS  . 'classes',
ROOT . DS . 'application',
);

set_include_path(join(PATH_SEPARATOR, $paths));
spl_autoload_register();

My router is a bit of a mess, but so far,

$url = explode('/', trim($_SERVER['REQUEST_URI'], '/'));

    $controller = !empty($url[0])  ? 'controller\\'.$url[0]  : 'controller\\home';
    $method = !empty($url[1]) ? $url[1] : 'index';
    $params = !empty($url[2]) ? $url[2] : $_POST;


    if (class_exists($controller)){

        $dispatchedController = "new $controller()";

        if (! method_exists($controller, $method)){
            trigger_error("{$controller}::{$method}() Method does not exist!");
            $error = new ErrorHandler();
            $error->invalidDispatch(debug_backtrace(),$controller, $method);
            return;
        }

        return $dispatchedController::$method;

    } else{
        trigger_error("{$controller}::{$method}({$params}) Method does not exist!");
        $error = new ErrorHandler();
        $error->invalidDispatch(debug_backtrace(), $controller, $method);
        return;
    }
}

However, it keeps failing on return $dispatchedController::$method;

Let's take for example, the class file home:

namespace controller;

class home
{
    public function index(){

    echo "cool!";
    }
}

I am being hit with the error: Fatal error: Class 'new controller\home()' not found in /public/library/intranet/classes/router.php on line 30

How do I modify the dispatcher?

bear
  • 11,364
  • 26
  • 77
  • 129

1 Answers1

0

You need to create your controller object by changing the code to

$dispatchedController = new $controller;

Then you can return the method as a callable, perhaps with

return array($dispatchedController, $method);

which can be then invoked with

call_user_func($returnedValue); // and also with call_user_func_array
Jon
  • 428,835
  • 81
  • 738
  • 806