Getting parameter action function Slim 4

I got an action route like this

`$app->get('/company/{id}', GetCompany::class);`

And the Action


class GetCompany extends Action
{
protected function action(): Response
{

    return $this->respondWithData(....);
}

}

How do I get the {id} inside the action() function?

Thanks

This would work if you use the __invoke method instead of the action() method as name.

Example:

<?php

namespace App\Action\Home;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final class HomeAction
{
    public function __invoke(
        ServerRequestInterface $request,
        ResponseInterface $response,
        array $args
    ): ResponseInterface {
        $id = $args['id'];
        
        $response->getBody()->write(sprintf('The ID is: %s', $id));

        return $response;
    }
}
1 Like

Thanks don’t you need to implement the “actions” class there?

Do you mean the “action” class method?

My example shows an “invokable” class. Slim will pass the request, response and the route arguments to the __invoke method if you use define the route like this: $app->get('/company/{id}', GetCompany::class);

This can be marked as resolved.
I only need in which folder this class should be. I will open a new thread.
Thanks