php - 无法使用 symfony 路由让路由在 php 应用程序中工作
问题描述
索引.php
require "vendor/autoload.php";
require "routes.php";
路由.php
<?php
require "vendor/autoload.php";
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
try {
$form_add_route = new Route(
'/blog/add',
array(
'controller' => '\HAPBlog\Controller\EntityAddController',
'method'=>'load'
)
);
$routes = new RouteCollection();
$routes->add('blog_add', $form_add_route);
// Init RequestContext object
$context = new RequestContext();
$context->fromRequest(Request::createFromGlobals());
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match($context->getPathInfo());
// How to generate a SEO URL
$generator = new UrlGenerator($routes, $context);
$url = $generator->generate('blog_add');
echo $url;
}
catch (Exception $e) {
echo '<pre>';
print_r($e->getMessage());
}
src/Controller/EntityAddController.php
<?php
namespace HAPBlog\Controller;
use Symfony\Component\HttpFoundation\Response;
class EntityAddController {
public function load() {
return new Response('ENTERS');
}
}
我指的是下面给出的教程:
但是当我尝试访问该站点时http://example.com/routes.php/blog/add 它给出了一个空白页面。通过 PHPStorm 调试显示没有进入“EntityAddController”类 上面的代码有什么问题?
解决方案
这个过程没有什么神奇的,一旦你得到路由信息,你就必须调用配置的控制器并发送响应内容。
在这里举一个完整的例子:
// controllers.php
class BlogController
{
public static function add(Request $request)
{
return new Response('Add page!');
}
}
// routes.php
$routes = new RouteCollection();
$routes->add('blog_add', new Route('/blog/add', [
'controller' => 'BlogController::add',
]));
// index.php
$request = Request::createFromGlobals();
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
try {
$attributes = $matcher->match($request->getPathInfo());
$response = $attributes['controller']($request);
} catch (ResourceNotFoundException $exception) {
$response = new Response('Not Found', 404);
} catch (Exception $exception) {
$response = new Response('An error occurred', 500);
}
$response->send();
推荐阅读
- mysql - 在Mysql中使用where子句获取重复记录
- vba - Access VBA - 使用变量调用表单模块中的子例程/函数
- python - 尝试...除了处理 matplotlib 版本
- python - Anaconda 无法打开,所有现有解决方案都不起作用
- python - 为什么我会收到“列表索引超出范围”错误?
- vim - How do you comment out all non-blank non-commented lines in a file?
- c++ - 如何使用list的unique_ptr的C++ unordered_map
- javascript - Capturing QRCode image from web-whatsapp
- r - 如何在 R 中使用 for 循环处理数据帧?
- react-native - React Native 如何创建一个 createStackNavigator