I am creating an API using the Slim framework. Currently I use a single file to create the route and pass a closure to it:
$app->get('/', function($req, $resp){
//Code...
})
But I realise that my file has grown rapidly. What I want to do is use controllers instead, so I will have a controller class and just pass the instance/static methods to the route, like below
class HomeController
{
public static function index($req, $resp){}
}
and then pass the function to the route
$app->get('/', HomeController::index);
I tried this, but it does not work, and I wonder if there is a way I can use it to manage my files.
PHP 5.6 Slim 2.6.2
Update: PHP 5.6 Slim 3.0.0
The problem with class based routing in Slim 3.0 is access to
$this
/$app
. I think you will need to useglobal $app
to access it.In my pet project I use route groups with
require_once
. Something likeLooks not as beauty as could be with pure classes but works like expected with all features accessible without additional coding.
Turn the controller into a functor:
and then route like this:
For reference, see
Nikic's Fast Route is a very minimal router, so some of the niceties of the bigger frameworks are removed. Here's a basic solution:
routes.php
controller use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response;
Smooth & short way to use a controller as an object (not a static way)
The Controller\MyClass is resolved through the use of PSR autoload
Here's an example:
Controller
Application
Profit!
This method is described in the documentation click me