douyiyang6317 2012-11-21 00:00
浏览 84
已采纳

修改我的调度员

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?

  • 写回答

1条回答 默认 最新

  • droc60607 2012-11-21 00:03
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置