[英]PHP: PSR-4 class not found?
找不到類'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
無法找到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']);
進行一些更改以使其起作用。
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?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.