PHP Slim 框架创建控制器

2022-01-05 00:00:00 php slim slim-3 controller

我正在使用 Slim 框架创建 API.目前我使用单个文件来创建路由并向它传递一个闭包:

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){}
}

然后将函数传递给路由

$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.

推荐答案

将控制器变成函子:

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

然后像这样路由:

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

参考,见

  • http://www.slimframework.com/docs/objects/router.html#how-to-create-routes
  • http://www.slimframework.com/docs/objects/router.html#route-callbacks.

相关文章