0

我必须验证文件的一些属性,将它们转换为 png 并将它们移动到亚马逊 S3 服务,但只有在控制器中的验证成功时我才需要将文件移动到存储桶,客户要求是使用中间件为达到这个。即使需要使用 $request-> withAttribute() 有没有办法做到这一点?

4

1 回答 1

1

确实是的。中间件只是可调用堆栈的另一层。

它是在您的代码中定义之前还是之后应用:

<?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();

这将输出此 HTTP 响应正文:

BEFORE Hello AFTER

所以,在你的情况下,我会选择这样的东西:

<?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
        }
    }
}
于 2016-12-19T22:16:38.340 回答