php - PHP - Middlewares\FastRoute 包的 nikic/FastRoute 路由
问题描述
我有这些路线:
['GET', '/article/{id}', ['SuperBlog\Controller\ArticleController', 'show']],
我正在使用Middleware\FastRoute
,Middle\RequestHandler
和Relay
包来制作请求处理程序。我也在使用php-di
DI 容器。
我的问题是,如果我想使用上面提到的路线,我给了我这个错误:
Deprecated: Non-static method SuperBlog\Controller\ArticleController::show() should not be called statically in
当我不使用方法(如['GET', '/', 'SuperBlog\Controller\HomeController'],
)时,它运行良好。
我的问题是我怎样才能让它工作?没有找到任何解决方案。我知道如果我将show
方法设为静态它会起作用,但我认为这不是一个好主意。
引导程序.php
/**
* Routing
*/
$routes = simpleDispatcher(function (RouteCollector $r){
$routes = include('routes.php');
foreach ($routes as $route) {
$r->addRoute($route[0], $route[1], $route[2]);
}
});
$middlewareQueue[] = new FastRoute($routes);
$middlewareQueue[] = new RequestHandler($container);
$requestHandler = new Relay($middlewareQueue);
$response = $requestHandler->handle(ServerRequestFactory::fromGlobals());
$emitter = new SapiEmitter();
return $emitter->emit($response);
文章控制器.php
class ArticleController
{
/**
* @var ArticleRepository
*/
private $articleRepository;
/**
* @var Twig_Environment
*/
private $twig;
/**
* @var ResponseInterface
*/
private $response;
public function __construct(ArticleRepository $articleRepository, Twig_Environment $twig, ResponseInterface $response) {
$this->articleRepository = $articleRepository;
$this->twig = $twig;
$this->response = $response;
}
public function show($request) {
$article = $this->articleRepository->get($request->getAttribute('id'));
$this->response->getBody()->write($this->twig->render('article.twig',[
'article' => $article,
]));
return $this->response;
}
}
路由.php
return [
['GET', '/', 'SuperBlog\Controller\HomeController'],
['GET', '/article/{id}', ['SuperBlog\Controller\ArticleController', 'show']],
];
解决方案
Try this:
/**
* Routing
*/
$routes = simpleDispatcher(function (RouteCollector $r){
$routes = include('routes.php');
foreach ($routes as $key => $route) {
$r->addRoute($route[$key][0], $route[$key][1], $route[$key][2]);
}
});
因为它是一个多维数组,所以您将包含在“routes.php”中。
推荐阅读
- javascript - 状态不会在异步函数中更新
- amazon-web-services - AWS lambda 在同一 aws 账户中担任角色以访问 S3
- javascript - 如何以及在哪里访问 gatsby 中的 html 正文
- javascript - 多步验证变量
- c# - 在 Asp.Net core 中上传图片失败
- selenium - Selenium 脚本在每一步都失败,异常“noSuchElementFound”
- electron - 使用包含在字符串中的 HTML 来馈送 Electron 的 webview
- java - 来自 Java Spring Boot 的 AWS RDS 代理连接
- android - 无法在 react-native-webview 的 Quill 编辑器中插入图像
- javascript - 使用 fetch API 进行流式传输