【问题标题】:Calling an internal api within another api in using Slim Framework使用 Slim 框架在另一个 api 中调用内部 api
【发布时间】:2015-06-26 04:49:51
【问题描述】:

早安,

我正在尝试使用 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' 中调用 db 处理 Api '/api/getListAdmin'。

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

  • 方法 1(使用 file_get_contents)需要很长时间才能获取数据(在我的本地环境中为几秒钟)。

  • 方法 2 (router->getNamedRoute->dispatch) 似乎不起作用,因为即使我使用 $result = $route->dispatch(); 它也会在视图中呈现结果将结果存储在变量中,但似乎调度方法仍将结果呈现到屏幕上。

我尝试仅为 db 相关 API 创建一个新的超薄应用程序,但仍然调用其中一个需要相当长的时间 2 到 3 秒。

如果有人可以帮助我解决我做错了什么或者从另一个 api 获取数据的正确方法是什么,我真的很感激。

谢谢

【问题讨论】:

    标签: php web-services api slim


    【解决方案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
        ));
    });
    

    方法二

    如果你对过度杀伤方法没问题,你可以使用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
      ));
    });
    

    【讨论】:

    • 谢谢,有用的库,我试过了,但它仍然在我的项目结构中,响应速度很慢,原因可能是将 api 调用视为外部调用并重新实例化 slim。
    • @DonDiegoDelavega 检查我的更改。
    猜你喜欢
    • 2020-03-20
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 2017-11-21
    相关资源
    最近更新 更多