1

I'm developing Web API with Slim Framework 4. Nothing special, everything as usual. Request handlers are something like:

$app = \Slim\Factory\AppFactory::create();
...
$app->get('/resource', function($request, $response)
{
    $response->getBody()->write(json_encode(/* some data */));
    return $response->withHeader('Content-Type', 'application/json');
});
...
$app->run();

However at some point inside one of handlers I need to invoke my own API method and get its result. For example: assume there is a special API method for batch invocation. It accepts a list of GET resources and responds with an array of results where every element of that array is a result of API invocation for corresponding API URL:

$app->post('/batch', function($request, $response)
{
    $urls = $request->getParsedBody();

    $results = [];

    foreach($urls as $url)
    {
        $results[] = /* invoke my own API with method = GET and uri = $url, and push result into array */
    }

    $response->getBody()->write(json_encode($results));
    return $response->withHeader('Content-Type', 'application/json');
});

This should be done somehow with the same Slim App instance. However I couldn't find anything about that in Slim documentation. Currently I'm researching Slim source code, but may be you guys already know the answer?

nyan-cat
  • 610
  • 5
  • 19
  • A probably-obvious outside-the-box solution is to make your request handlers into normal named functions / methods, so you can call them directly. But forwarding to another handler is a common framework facility, so the question seems reasonable. – IMSoP Jun 02 '22 at 23:24
  • That would be not as convenient as I would like to. I would still need to parse URLs, decompose them into arguments with the same rules Slim does, which is tricky. – nyan-cat Jun 02 '22 at 23:37
  • It depends on your use case, but you could invoke the $app->handle($request) method with a custom request object to make a sub-request. IMSop already pointed into the right direction. I suggest: If you put your business logic into (service) classes, then each of your route handler could use that shared class. – odan Jun 03 '22 at 07:04

0 Answers0