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

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

问题描述

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

参考,见

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

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