[英]PSR-4 Autoloading option is not loading classes in my project?
當我嘗試使用 psr-4 自動加載選項加載我的類時,我收到此錯誤“致命錯誤:未捕獲的錯誤:在 C:\xampp\htdocs\gacho\App\Core\Application.php:17 中找不到類 'HomeController'堆棧跟蹤:#0 C:\xampp\htdocs\gacho\public\index.php(16): App\Core\Application->__construct() #1 {main} 在 C:\xampp\htdocs\gacho\App 中拋出第 17 行的 \Core\Application.php '這是我的代碼結構和代碼:
代碼結構:
|gacho
|- App
|- Controller
|- HomeController.php
|- Core
|- Application.php
|- Model
|- View
|-public
|- .htaccess
|- index.php
|-vendor
|- composer
|- autoload_classmap.php
|- autoload.php
|-composer.json
索引.php:
<?php
use App\Core\Application;
define('ROOT', dirname(__DIR__) . DIRECTORY_SEPARATOR);
define('APP', ROOT . 'App' . DIRECTORY_SEPARATOR);
define('CONTROLLER', ROOT . 'App' . DIRECTORY_SEPARATOR . 'Controller' .
DIRECTORY_SEPARATOR);
define('VIEW', ROOT . 'App' . DIRECTORY_SEPARATOR . 'View' .
DIRECTORY_SEPARATOR);
define('MODEL', ROOT . 'App' . DIRECTORY_SEPARATOR . 'Model' .
DIRECTORY_SEPARATOR);
define('CORE', ROOT . 'App' . DIRECTORY_SEPARATOR . 'Core' .
DIRECTORY_SEPARATOR);
$modules = [ROOT, APP, CORE, CONTROLLER];
require_once __DIR__ . '\..\vendor\autoload.php';
$app = new Application();
作曲家.json:
{
"autoload": {
"psr-4": {
"App\\": "App/"
}
}
}
應用程序.php:
<?php
namespace App\Core;
use App\Core\Controller;
use App\Controller\HomeController;
class Application
{
protected $controller = 'HomeController';
protected $action = 'index';
protected $params = [];
public function __construct()
{
$this->prepareURL();
if (file_exists(CONTROLLER. $this->controller . '.php')) {
$this->controller = new $this->controller;
if (method_exists($this->controller, $this->action)) {
call_user_func_array([$this->controller, $this->action], $this->params);
}
}
}
protected function prepareURL()
{
$request = trim($_SERVER['REQUEST_URI'], '/');
if (!empty($request)) {
$url = explode('/', $request);
$this->controller = isset($url[0]) ? $url[0].'Controller' : 'HomeController';
$this->action = isset($url[1]) ? $url[1] : 'index';
unset($url[0], $url[1]);
$this->params = !empty($url) ? array_values($url) : [];
}
}
}
HomeController.php:
<?php
namespace App\Controller;
use App\Core\Controller;
class HomeController extends Controller
{
public function index($id= '', $name='')
{
$this->view('home\index', [
'name' => $name,
'id' => $id
]);
$this->view->page_title = 'Home Page';
$this->view->render();
}
public function users()
{
$this->view('home\users', []);
$this->view->page_title = 'Users';
$this->view->render();
}
}
FQCN 是App\Core\Application
,路徑是app\core\Application.php
。 使用 PSR-4 它將嘗試從App\Core\Application.php
加載,但該路徑不存在(至少在區分大小寫的文件系統中不存在)。
您最好的選擇是更改目錄結構以匹配名稱空間。 它們需要完全匹配,包括大小寫。
嘗試運行此命令: composer update
請檢查您的 .env 文件和數據庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.