SlimPhp微框架上的Api路由模式?
问题描述:
是否存在一些路线模式以及如何使用SlimPhp编写结构?SlimPhp微框架上的Api路由模式?
一样,我做了一个API文件夹与index.php文件来存储所有我的路线:
$app->get('/api/shirt/{id}', function (Request $request, Response $response) {
//CODE
});
$app->get('/api/some-other-endpoint/{id}', function (Request $request, Response $response)
//CODE
});
但一段时间后,我意识到,我的索引文件会得到相当大的。
那么,我该如何管理我的端点路由?使用类,控制器,动作?
我在哪里可以找到有关这些特定概念的文档?
答
我正在使用控制器(在本例中命名为Action),并且仍然在一个文件中具有所有路由。
此外,我使用分组无论我可以因为它给一个更好的结构(在我看来)。 我尝试使Action-classes尽可能小,我不需要查看路由文件来获取我想要更改的类。
下面的例子:
路线 - 文件:
$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
}
}
+0
这与我的想法非常相似,并且认为我可以将这样的东西应用到我的项目中。因为我喜欢使用类。 –
答
我通常有我自己的路由器之前,我涉及修身的路由器来决定使用基于域名之后的路径上哪条路线:
公共/ index.php文件
chdir(dirname(__DIR__));
require_once 'vendor/autoload.php';
$app = new Slim\App;
require 'app/routes/index.php';
$app->run();
应用程序/路由/指数.php
$_url = parse_url($_SERVER['REQUEST_URI']);
$_routes = explode('/',$_url['path']);
$_baseRoute = $_routes[1];
switch ($_baseRoute) {
case 'api':
$_routeFile = 'app/api/' . $_routes[2] . '.php';
break;
default:
$_routeFile = 'app/routes/' . $_baseRoute . '.php';
break;
}
if (file_exists($_routeFile)) {
require $_routeFile;
}
else {
die('Invalid API request');
}
要构建的API快你可能想切换到Laravel和使用[资源管理器](https://laravel.com/docs/5.4/controllers#resource-controllers)。相同的路由语法! –
我会阅读关于laravel。但我试图找到一些使用苗条的PHP解决方案。像一些控制器包一样,因为我想保持使用slim而不是改变框架。 –