使用 Slim Framework 在另一个 api 中调用内部 api

Calling an internal api within another api in using Slim Framework

美好的一天,

我正在尝试使用 Slim 框架开发一个网络平台。我已经以 MVC 方式完成了。我的一些 APIs 用于渲染视图,一些只是为了从数据库中获取数据而构建的。 例如:

$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
    ));
});

我正在尝试在与 apis '/adminpage' 相关的视图中调用数据库处理 Api '/api/getListAdmin'。

根据我在网上找到的解决方案,我尝试了方法 1 和 2,但是:

我尝试为数据库相关的应用程序创建一个新的 slim 应用程序 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
    ));
});

方法二

如果您可以使用矫枉过正的方法,您可以使用 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
  ));
});