[英]Calling an internal api within another api in using Slim Framework
美好的一天,
我正在嘗試使用Slim框架開發Web平台。 我已經用MVC的方式做到了。 我的一些API用於呈現視圖,而某些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(使用file_get_contents)需要很長時間才能獲取數據(在我的本地環境中只有幾秒鍾)。
方法2(router-> getNamedRoute-> dispatch)似乎不起作用,因為即使我使用$ result = $ route-> dispatch(),它也會在視圖中呈現結果; 將結果存儲在變量中,但似乎dispatch方法仍將結果呈現到屏幕上。
我嘗試僅為與數據庫相關的API創建一個新的苗條應用程序,但仍然調用其中一個需要2至3秒的相當長的時間。
如果有人可以幫助我解決我做錯的事情或從另一種api獲取數據的正確方法是什么,請多謝。
謝謝
這可能是創建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
));
});
$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
));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.