【发布时间】:2018-06-03 20:28:26
【问题描述】:
我有一个页面,它使用相同的 HTTP 方法向 API 发出多个请求并显示结果。
<?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);
});
【问题讨论】:
-
我不知道你在这里寻找什么。您想将它们组合起来,但在问题的最后,您说您不想将请求组合到一个端点中。你有什么想法?
-
@EatPeanutButter 希望组合更加通用,每个端点都可以以某种方式一起发送。理想情况下,这将是一种标准的苗条方法。