There is a way to execute a Middleware after controller using withAttribute in the request? (slim 3)

335 views Asked by At

I have to validate some attributes to the files , convert them to png and move them to amazon S3 service , but i need to move the file to the bucket only if the validation in controller is successful, the customer requirement is to use a middle ware to achieve this. is there a way to do it even when is necessary to use the $request-> withAttribute() ?

1

There are 1 answers

0
Georgy Ivanov On

Yes, indeed. Middleware is just another layer of your callable stack.

Whether it is applied before or after is defined within your code:

<?php
// Add middleware to your app
$app->add(function ($request, $response, $next) {
    $response->getBody()->write('BEFORE');
    $response = $next($request, $response);
    $response->getBody()->write('AFTER');

    return $response;
});

$app->get('/', function ($request, $response, $args) {
    $response->getBody()->write(' Hello ');

    return $response;
});

$app->run();

This would output this HTTP response body:

BEFORE Hello AFTER

So, in your case I'd go for something like this:

<?php
class AfterMiddleware
{
    public function __invoke($request, $response, $next)
    {
        // FIRST process by controller
        $response = $next($request, $response);

        // You can still access request attributes
        $attrVal = $request->getAttribute('foo');

        // THEN check validation status and act accordingly

        $isValid = true;

        if ($isValid) {
            // Send to the bucket
        }
    }
}