Slim应该如何用于合并多个REST请求?
我有一个页面使用相同的HTTP方法向API发出多个请求并显示结果。Slim应该如何用于合并多个REST请求?
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, "https://rest.api.com/staff");
$staff=curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, "https://rest.api.com/departments/accounting");
$departments=curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, "https://rest.api.com/roles");
$roles=curl_exec($ch);
curl_close($ch);
echo $twig->render('offices.html', ['staff'=>$staff,'departments'=>$departments,'roles'=>$roles]);
该API位于https://rest.api.com,并且在我的控制之下。三个端点有时需要单独访问,因此必须保持。
<?php
$app = new \Slim\App();
$app->get('/users', function ($request, $response, $args) {
return $response->withJson(getUsers(),200);
});
$app->get('/departments/{subdept}', function ($request, $response, $args) {
return $response->withJson(getDepartments($args['subdept']),200);
});
$app->get('/roles', function ($request, $response, $args) {
return $response->withJson(getRoles(),200);
});
// other endpoints...
$app->run();
这三个请求应该如何组合成一个请求?我不想做类似以下的事情,因为它不灵活,并且需要每个组合端点的附加文档。
$app->get('/users_and_departments_and_roles', function ($request, $response, $args) {
return $response->withJson([
'users'=>getUsers(),
'departments'=>getDepartments($args['subdept']),
'roles'=>getRoles()
],200);
});
也许合并请求是不是你想要达到的最好的说明,因为我不认为我们实际上可以结合 HTTP请求。如果您想使用POST
方法,这可能会更容易,但使用GET
方法实现此目的可能是一种路由模式,可用于根据呼叫方的要求返回user
,role
和department
的多个组合。
假设只有数值是可以接受的subdept
为简单起见,这里是为了表达我对解决方案总体思路的例子:
$app->get('/api/combine/user:{users_required:true|false}/role:{roles_require:true|false}/department:{subdept:[0-9]+|false}', function ($req, $res, $args) {
return $response->withJson([
'users'=> $args['users_required'] == 'true' ? getUsers() : [],
'departments'=> $args['subdept'] == 'false' ? [] : getDepartments($args['subdept']),
'roles'=> $args['roles_required'] == 'true' ? getRoles() : []
],200);
});
这条路线将随时返回包括users
,roles
和结果departments
密钥,但这些密钥可能包括空数组作为值,如果调用者不希望任何人,这是达主叫方,但主叫必须指定,如果他不希望任何这些键的或不和路线的顺序参数始终相同。例如,一个可以访问https://rest.api.com/user:false/role:true/department:100
得到一个结果忽略用户(/用户:假),角色的列表(/角色:真)为subdept=100
和部门(/deptartment:100)。
一个更为复杂的模式可以帮助你,但总的想法是,以确定哪些可以决定要提供的各个端点用户的什么样的组合,并返回基于该结果的路由模式。
很抱歉的坏的描述,但你猜正是笏我的意思是说。让我尝试申请。谢谢 – user1032531
不客气。希望能帮助到你。 – Nima
我不知道你在找什么。你想合并它们,但是在你的问题结束时,你会说你不想将请求合并到一个端点中。你有什么想法呢? – WillardSolutions
@EatPeanutButter通缉的组合是更通用的,每个端点会以某种方式一起发送。理想情况下,这将是一种标准的细长方法。 – user1032531