Calling an internal api within another api in using Slim Framework

混江龙づ霸主 提交于 2020-01-04 19:06:48

问题


Good day,

Im trying to develop a web platform using Slim framework. I've done it in MVC way. some of my APIs are used to render the view and some is just built to get data from the db. for example :

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

I'm trying to call the db handling Api '/api/getListAdmin' within the view related apis '/adminpage'.

based on solutions i have found in the web i tried method 1 and 2 but:

  • method 1 (using file_get_contents) take a long time to get the data (few seconds on my local environment).

  • method 2 (router->getNamedRoute->dispatch) seems dosnt work becuz it will render the result in the view even if i use $result = $route->dispatch(); to store the result in a variable but seems dispatch method still render to result to the screen.

I tried to create a new slim app only for db related API but still calling one of them takes quite long time 2 to 3 seconds.

Really appreciate it if some one can help me on what i'm doing wrong or what is the right way to get data from another api.

Thanks


回答1:


Method 1

This could be another method, creating a Service layer, where redundant code is deleted:

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

Method 2

If you are ok with an overkill method, you could use 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
  ));
});


来源:https://stackoverflow.com/questions/30971542/calling-an-internal-api-within-another-api-in-using-slim-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!