PHP Slim Framework Create Controller

James Okpe George picture James Okpe George · Dec 31, 2015 · Viewed 17.3k times · Source

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.

Answer

localheinz picture localheinz · Dec 31, 2015

Turn the controller into a functor:

class HomeController
{
    public function __invoke($req, $resp) {}
}

and then route like this:

$app->get('/', HomeController::class);

For reference, see