我刚刚开始尝试创建一个简单的路由器(我尝试了几种解决方案,例如 AltoRouter,但没有任何效果,我想开始一个非常简单的解决方案)。 Composer 自动加载无法到达命名空间。
致命错误:未捕获错误:在 C:\larragon\www 中找不到类“App\Router” external\index.php:6 堆栈跟踪: #0 {main} 抛出在 C:\larragon\www 中 第 6 行的 external\index.php
我做了“composer dump-autoload”和“composer更新命令”,甚至尝试了自制的自动加载器。
这是我的项目的架构:
来源
> Router
Router
Route
供应商
autoload
这是我的composer.json
{
"name": "root/router",
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"authors": [
{
"name": "********",
"email": "************"
}
],
"require": {}
}
这是我的.htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
这是我的index.php
<?php
require './vendor/autoload.php';
use App\Router;
$router = new Router($_GET[$url]);
$router->get('/home', function(){ echo 'welcome on home page'; });
$router->run();
这是我的路由器类
<?php
namespace App;
use App\Route;
class Router {
public $url;
private $routes = [];
public function __construct($url)
{
$this->url = $url;
}
public function get($path, $callable)
{
$route = new Route($path, $callable);
$this->routes['GET'][] = $route;
}
public function post($path, $callable)
{
$route = new Route($path, $callable);
$this->routes['POST'][] = $route;
}
public function run()
{
echo '<pre>';
echo print_r($this->routes);
echo '</pre>';
}
}
这是我的 Route.php 类
<?php
namespace App;
class Route {
public function __construst($path, $callable)
{
$this->path = $path;
$this->callable = $callable;
}
}
我认为问题可能出在命名空间上。 试试这个:
namespace App\Router
然后输入
composer dump-autoload