未找到类'LoginController‘,我使用PSR-4自动加载所有控制器。
"autoload": {
"psr-4": {
"App\\": "app/"
}
}在这里,当我需要调用控制器上的方法时,我只需找到类,创建该类的一个新实例,然后调用我刚刚创建的类上的方法。
if (!isset($result['error'])) {
$handler = $result['handler'];
$class = $handler[0];
$class = substr($class, strrpos($class, '\\') + 1);
$class = new $class();
$method = $handler[1];
var_dump($class); // it doesn't get this far
$class->$method();
} 由于某些原因,$class = new $class();行抛出了无法找到的LoginController.php,但我确信PSR-4自动加载器是用来自动加载它的?
<?php declare(strict_types = 1);
namespace App\Controllers\Frontend\Guest;
class LoginController
{
public function getView()
{
echo 'it worked?';
}
}通往LoginController的路径是/app/Controllers/Frontend/Guest/LoginController.php,我这样声明我的路线,
$router->get('/', ['App\Controllers\Frontend\Guest\LoginController', 'getView']);发布于 2018-02-11 01:07:22
做些改变,让它发挥作用。
psr-4中的/斜杠并不重要,但也不是必需的。
{
"require": {
"baryshev/tree-route": "^2.0.0"
}
"autoload": {
"psr-4": {
"App\\": "app"
}
}
}我不认为需要包含require 'vendor/autoload.php';,所以composer可以自动加载您的类/包。
好的,假设在这里,下面的代码本质上是在命名空间中命名的,您不想这样做,因为您需要名称空间作为编写器类名的一部分,以便自动加载它:
$class = $handler[0];
$class = substr($class, strrpos($class, '\\') + 1);
$class = new $class();相反,只需使用$result['handler'][0]的全部值。
此外,您应该检查两个类是否都存在,并且该方法是否存在于该类中,这样您就可以处理任何错误,因为路由匹配但在代码中不存在。(该路由器不检查类是否存在)。
所以是一个有用的例子:
<?php
require 'vendor/autoload.php';
$router = new \TreeRoute\Router();
$router->addRoute(['GET', 'POST'], '/', ['App\Controllers\Frontend\Guest\LoginController', 'getView']);
$method = $_SERVER['REQUEST_METHOD'];
$url = $_SERVER['REQUEST_URI'];
$result = $router->dispatch($method, $url);
if (!isset($result['error'])) {
// check controller
if (class_exists($result['handler'][0])) {
$class = $result['handler'][0];
$class = new $class();
// check method
if (method_exists($class, $result['handler'][1])) {
$class->{$result['handler'][1]}($result['params']);
} else {
// method not found, do something
}
} else {
// controller not found, do something
}
}
else {
switch ($result['error']['code']) {
case 404 :
echo 'Not found handler here...';
break;
case 405 :
$allowedMethods = $result['allowed'];
if ($method == 'OPTIONS') {
echo 'OPTIONS method handler here...';
}
else {
echo 'Method not allowed handler here...';
}
break;
}
}对此进行了测试,并使用了以下文件系统结构,您在问题中也提到了这一点--如果它不一样,它将无法工作。

对LoginController.php没有任何更改,这很好。
结果:
it worked?https://stackoverflow.com/questions/48726692
复制相似问题