1

I'm using the PHP Slim Framework v3 to make a web app and the routes I have are all typically divided into either a frontend route or an API endpoint. I have a frontend route where I want to call an API endpoint to get data to display. For example:

Frontend Route

$app->get('/order/{order-id}', function(Request $request, Response $response, array $args) {
    $order_id = intval($args['order-id']);
    $order_details = ______; // API endpoint call to get the order details

    $response = $this->view->render($response, 'order-details.html', [
        'order_details' => $order_details
    ]);

    return $response;
});

API Endpoint

$app->get('/api/order/{order-id}', function(Request $request, Response $response, array $args) use ($db) {
    $order_id = intval($args['order-id']);
    $order_details = $db->order_details($order_id); // Query the database for all the order details

    $response = $response->withJson($order_details);
    return $response;
});

What can I put in place of the ______ so I can grab the JSON being returned by the /api/order/{order-id} call?


Please note that I'm considering using Guzzle to do this, but I feel like that's such an overkill for what I'm trying to do here. I would like to think that Slim already has a way for me to do what I'm attempting to achieve.

halfer
  • 19,824
  • 17
  • 99
  • 186
dokgu
  • 4,957
  • 3
  • 39
  • 77
  • If this is in the same app, why not factor out the processing and call a function (or class method) with the parameters needed. It's a much simpler and quicker process than making an API call. – Nigel Ren Aug 30 '22 at 17:49
  • I just started learning how to use Slim, I'm not actually familiar with the best practices. But I think I found a solution using `subRequest()`. I'm just about to write it out. – dokgu Aug 30 '22 at 17:54
  • Worth checking [this about Slim 4](https://bariseser.medium.com/slim-4-0-0-has-been-released-b6793f591a7f) which has *The App::subRequest() method has been removed. You can perform sub-requests via $app->handle($request) from within a route callable.* – Nigel Ren Aug 30 '22 at 18:01

1 Answers1

0

From trying a few solutions out, I was able to use subRequest() for this:

$app->get('/order/{order-id}', function(Request $request, Response $response, array $args) use ($app) {
    $order_id = intval($args['order-id']);
    $order_details = $app->subRequest('GET', '/api/order/' . $order_id)->getBody(); // API endpoint call to get the order details
    $order_details = json_decode($order_details);

    $response = $this->view->render($response, 'order-details.html', [
        'order_details' => $order_details
    ]);

    return $response;
});

Seems to work for me, but this may not be the best solution as I am still just learning how to use Slim. Other better answers are welcome!

dokgu
  • 4,957
  • 3
  • 39
  • 77