Class' 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']);
答案 0 :(得分:2)
进行一些更改,以使其有效。
不重要但也不是必需的是psr-4中的/斜杠
{
"require": {
"baryshev/tree-route": "^2.0.0"
}
"autoload": {
"psr-4": {
"App\\": "app"
}
}
}
我没有看到您需要包含的require 'vendor/autoload.php';
,因此作曲家可以自动加载您的课程/套餐。
好的假设在那里,下面的代码基本上是命名空间的基本名称,你不想这样做,因为你需要命名空间作为作曲家类名的一部分自动加载它:
$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?