你好,
我正在尝试使用Slim框架开发一个web平台。我已经用MVC的方式完成了。我的一些API用于呈现视图,而另一些只是用来从数据库中获取数据。例如:
$app->get('/api/getListAdmin', function () use ($app) {
$data = ...//code to get admins' list
echo json_encode($data);
})->name("getListAdmin");
$app->get('/adminpage', function () use ($app) {
// **** METHOD 1 :// get the data using file_get_contents
$result = file_get_contents(APP_ROOT.'api/getListAdmin');
// or
// **** METHOD 2 :// get data using router
$route = $this->app->router->getNamedRoute('getListAdmin');
$result = $route->dispatch();
$result = json_decode($result);
$app->render('adminpage.php', array(
'data' => $result
));
});
我试图在视图相关的Api"/adminpage"中调用数据库处理Api"/Api/getListAdmin"。
基于我在网上找到的解决方案,我尝试了方法1和2,但:
方法1(使用fileget_contents)需要很长时间才能获得数据(在本地环境中需要几秒钟)。
方法2(router->getNamedRoute->dispatch)似乎不起作用,因为即使我使用$result=$route->dispach(),它也会在视图中呈现结果;将结果存储在一个变量中,但调度方法似乎仍然会将结果呈现到屏幕上。
我试着只为数据库相关的API创建一个新的瘦应用程序,但仍然调用其中一个需要2到3秒的很长时间。
如果有人能帮助我做错事,或者从另一个api获取数据的正确方法是什么,我真的很感激。
感谢
方法1
这可能是另一种方法,创建一个Service
层,删除冗余代码:
class Api {
function getListAdmin() {
$admins = array("admin1", "admin2", "admin3"); //Retrieve your magic data
return $admins;
}
}
$app->get('/api/getListAdmin', function () use ($app) {
$api = new Api();
$admins = $api->getListAdmin();
echo json_encode($admins);
})->name("getListAdmin");
$app->get('/adminpage', function () use ($app) {
$api = new Api();
$admins = $api->getListAdmin();
$app->render('adminpage.php', array(
'data' => $admins
));
});
方法2
如果你可以接受过度杀伤方法,你可以使用Httpful:
$app->get('/adminpage', function () use ($app) {
$result = 'Httpful'Request::get(APP_ROOT.'api/getListAdmin')->send();
//No need to decode if there is the JSON Content-Type in the response
$result = json_decode($result);
$app->render('adminpage.php', array(
'data' => $result
));
});