Request/response customization

as someone that went the “custom” request / response route. (and had a fight with odan :stuck_out_tongue: ) i can safely say… dont bother with custom request / response. it WILL make your life harder (ive gone back to “mostly” vanilla slim as it really really just works)

what i now use instead is a middleware that sets up the “parameters” onto the normal $request->getAttribute()

// TODO: sanitize the inputs
        foreach ((array)$request->getQueryParams() as $key => $value) {
            $request = $request->withAttribute("GET." . $key, $value);
        }
        foreach ((array)$request->getParsedBody() as $key => $value) {
            $request = $request->withAttribute("POST." . $key, $value);
        }

        foreach ((array)$route->getArguments() as $key => $value) {
            $request = $request->withAttribute("PARAM." . $key, $value);
        }

then usage in the controller is simply $request->getAttribute("POST.name");

also this might be of some use to you as well

as for the response…

go with something like

use System\Responders\Responder;
class JobsController {
    function __construct(
        protected Responder $responder,
    ) { }

    public function __invoke(Request $request, Response $response): Response {

    	// ...

    	return $this->responder->withResponse(
            response: $response,
            data: $data,
            errors: $errors,
        );
    }
}

this lets you use your container (php-di?) in the responder as well. gives you a TON of extra options for a few bits of extra boiler plate. but it makes it super easy to switch our responders then

slim middleware is super super super strong.

1 Like