Reputation: 679
I have got these route:
['GET', '/article/{id}', ['SuperBlog\Controller\ArticleController', 'show']],
and I am using Middleware\FastRoute
, Middle\RequestHandler
and Relay
packages to make a Request Handler. Also I am using php-di
DI container.
My problem is that if I want to use a route like mentioned above, i gaves me this error:
Deprecated: Non-static method SuperBlog\Controller\ArticleController::show() should not be called statically in
It works well when I don't use methods (like ['GET', '/', 'SuperBlog\Controller\HomeController'],
).
My question is how can I make it work? Didn't find any solution. I know that if I make the show
method static it will work, but I don't think it's a good idea.
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']],
];
Upvotes: 2
Views: 2644
Reputation: 1
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]);
}
});
As it is a multidimensional array you are including from 'routes.php'.
Upvotes: 0