我想用纯 php 做路由,但后来魔鬼拉我安装 symfony/router,现在我觉得自己像个白痴。我在连接课程时遇到问题,我按照说明进行操作并得到:
Fatal error: Uncaught Error: Class 'AppController' not found in /home/vagrant/html/phb/vendor/symfony/http-kernel/Controller/ControllerResolver.php on line 151
这是他喝的:
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\HttpKernel;
use App\Http\Controller\AppController;
$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/../.env');
$request = Request::createFromGlobals();
$routes = new RouteCollection();
$routes->add('main', new Route('/',
array(
'_controller' => 'AppController::index',
)
)
);
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
$resolver = new HttpKernel\Controller\ControllerResolver();
try {
$request->attributes->add($matcher->match($request->getPathInfo()));
$controller = $resolver->getController($request);
$arguments = $resolver->getArguments($request, $controller);
$response = call_user_func_array($controller, $arguments);
} catch (ResourceNotFoundException $e) {
$response = new Response('Not found', 404);
} catch (Exception $e) {
$response = new Response('Error occurred', 500);
}
$response->send();
我做的愚蠢在哪里?
尝试这样做:
这是为什么?因为您将作为字符串传递给对象
Route
,并且该类将包含AppController
在那里,并且没有声明use App\Http\Controller\AppController
。也可以使用php 5.3.0执行此操作,尽管该操作
index
不太可能为您工作(取决于类Route
):一般来说,整个功能是您传递完整的命名空间,因为 那里的课程将被匿名调用。并且常量
AppController::class
返回类的全名,即 如果您现在在文件中写入:你在文件中有什么:
什么写在
AppController
:注意Controller(s)这个词,你决定是否放一个字母)
另一个注释,你
composer.json
写了:但你必须: