SlimPhp微框架上的api路由模式? [英] Api route pattern on the SlimPhp microframework?
问题描述
是否存在一些路由模式,以及如何使用SlimPhp编写结构?
Is there some pattern of routes and how to write the structure using SlimPhp?
就像,我用index.php制作了一个api文件夹,用于存储我的所有路线:
Like, I made a api folder with a index.php to store ALL my routes:
$app->get('/api/shirt/{id}', function (Request $request, Response $response) {
//CODE
});
$app->get('/api/some-other-endpoint/{id}', function (Request $request, Response $response)
//CODE
});
但是一段时间后,我意识到索引文件会变得很大.
But after some time, I realized that my index file will get pretty big.
那么,我该如何管理我的端点路由?使用类,控制器,动作?
So, how can I manage my endpoint routes? Using classes, controllers, actions?
在哪里可以找到有关这些特定概念的文档?
Where can I find documentation about these particular concepts?
推荐答案
我正在使用控制器(在此示例中命名为Action),但所有路由都集中在一个文件中.
I'm using controller's (named Action's in this example) and still have all routing in one file.
此外,我会尽可能使用分组,因为它可以提供更好的结构(我认为). 我尝试使Action类尽可能的小,以至于不需要查看route-file来获取要更改的类.
Additionally I use grouping whereever I can because it give a better structure (in my opinion). I try to make the Action-classes as small as possible that I do not need to look at the routes-file for getting the class which I want to change.
这里有个例子:
路由文件:
$app->get('/user/{name}', [ShowUserAction::class, 'showUser'])->setName('user');
$app->get('/login', [LoginUserAction::class, 'showLogin'])->setName('login');
$app->group('/api', function () {
$this->get('/images', [ImagesApi::class, 'getImages'])->setName('api.images');
$this->get('/tags', [ImagesApi::class, 'getTags'])->setName('api.tags');
$this->get('/notifications', [UserNotificationsApiAction::class, 'getNotifications'])->setName('api.notifications');
$this->get('/bubbleCount', [BubbleCountApiAction::class, 'getBubbleCount'])->setName('api.bubbleCount');
});
$app->group('/review', function() use ($currentUser) {
$this->get('', [ReviewAction::class, 'showReviewOverview'])->setName('review.overview')->setName('review')
$this->get('/{type}', [ReviewAction::class, 'showReviewWithType'])->setName('review.type')
$this->get('/{type}/{id}', [ReviewAction::class, 'showReview'])->setName('review.type.id')
});
动作类:
class LoginUserAction
{
public function __construct() { } // with parameters
public function showLogin(Request $request, Response $response)
{
if ($this->currentUser->isLoggedIn()) {
return $response->withRedirect($this->router->pathFor('index'));
}
return $this->view->render($response, 'user/login.twig');
}
public function doLogin(Request $request, Response $response)
{
// check user name password and then login
}
}
这篇关于SlimPhp微框架上的api路由模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!