我试图通过实施动态路由器来推动我的迷你网站,所以我做了以下
<?php
use App\Controller\Autoloader;
use App\Controller\PostController;
require_once("controller/Autoloader.php");
Autoloader::register();
$url = $_SERVER['REQUEST_URI'];
$url = explode('/', $url);
array_shift($url);
$base = $url[0];
$url = $url[1];
$page = "";
$function = "";
$controller = "";
$urlArray = array(
'base' => $base,
'page' => $page,
'parameters' => array(
"controller" => $controller,
"function" => $function
)
);
$url = explode("?", $url);
$urlArray["page"] = $url[0];
$url = explode("&", $url[1]);
$urlArray['parameters']['controller'] = str_replace("controller=", "", $url[0]);
$urlArray['parameters']['function'] = str_replace("action=", "", $url[1]);
$controllerName = $urlArray['parameters']['controller'];
$controller = new $controllerName();
$controller->$urlArray['paremeters']['function']();
由于我的网址是 cleperduv2 / index.php?controller = PostController&amp; action = listPosts
我想调用控制器PostController.php上的函数listPosts
(!)致命错误:第40行的C:\ wamp64 \ www \ cleperduv2 \ index.php中找不到类'PostController'
答案 0 :(得分:0)
意思是:
$controller = new $controllerName();
使用此:
$controller = new "App\Controller\PostController";
如果您使用过laravel,您可能会注意到,在larevels路径中,控制器由完整的类名指定。即:
Route::get('/myIndexPage', 'Namespace1\Namespace2\MyController@index');
因此,根据相同的原则,您最好遵循约定在同一名称空间中定义控制器,因此您可以这样做:
$controller = new "App\Controllers\$controllerName";
答案 1 :(得分:0)
看起来像是命名空间,
你试过这样称呼它:
$namespace = "App\Controller\\";
$controllerName = $namespace . $urlArray['parameters']['controller'];
$controller = new $controllerName;
您可以下拉PostController的use namespace语句,这样就可以根据需要动态地声明和声明ll控制器!