PHP Slim Framework创建控制器 [英] PHP Slim Framework Create Controller

查看:109
本文介绍了PHP Slim Framework创建控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.

这篇关于PHP Slim Framework创建控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆