当我尝试使用PSR-4自动加载选项加载我的班,我得到这个错误“致命错误:未捕获的错误:类‘的HomeController’用C未找到:\ XAMPP \ htdocs中\ gacho \软件\核心\ Application.php:17堆栈跟踪:#0 C:\ XAMPP \ htdocs中\ gacho \公共\的index.php(16):应用程序\核心\应用 - > __构建体()#1 {主}扔在C:\ XAMPP \ htdocs中\ gacho \应用\ CORE \ Application.php上线17'这是我的代码结构及代码:
代码结构:
|gacho
|- App
|- Controller
|- HomeController.php
|- Core
|- Application.php
|- Model
|- View
|-public
|- .htaccess
|- index.php
|-vendor
|- composer
|- autoload_classmap.php
|- autoload.php
|-composer.json
index.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();
composer.json:
{
"autoload": {
"psr-4": {
"App\\": "App/"
}
}
}
Application.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
加载,但路径不存在(至少不是在一个文件系统区分大小写)。
你最好的选择就是改变目录结构相匹配的命名空间。他们需要完全匹配,包括大小写。