PHP-中间件\ FastRoute软件包的nikic / FastRoute路由

时间:2018-10-25 11:43:23

标签: php routes fastroute

我有这些路线:

['GET', '/article/{id}', ['SuperBlog\Controller\ArticleController', 'show']],

,我正在使用Middleware\FastRouteMiddle\RequestHandlerRelay软件包制作请求处理程序。我也在使用php-di DI容器。

我的问题是,如果我想使用上面提到的路由,我会给我这个错误:

Deprecated: Non-static method SuperBlog\Controller\ArticleController::show() should not be called statically in

当我不使用方法(例如['GET', '/', 'SuperBlog\Controller\HomeController'],)时,效果很好。

我的问题是如何使它起作用?找不到任何解决方案。我知道,如果我将show方法设为静态,它会起作用,但是我认为这不是一个好主意。

bootstrap.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);

ArticleController.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;
    }

}

routes.php

return [
    ['GET', '/', 'SuperBlog\Controller\HomeController'],
    ['GET', '/article/{id}', ['SuperBlog\Controller\ArticleController', 'show']],
];

1 个答案:

答案 0 :(得分:0)

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”中。