将阵列从控制器传递到中间件 Slim 3 PHP



我正在尝试将一个包含数据的数组传递给中间件,并根据Accept HTTP 标头对其进行格式化。
控制器从 db 获取数据,并应将其传递给响应对象。响应对象write()方法仅接受字符串:

public function getData(Request $request, Response $response): Response {
    return $response->write($this->getUsers());
    # This line of code should be fixed
}

中间件应获取响应并正确格式化:

public function __invoke(Request $request, Response $response, callable $next) {
    $response = $next($request, $response);
    $body = $response->getBody();
    switch ($request->getHeader('Accept')) {
        case 'application/json':
            return $response->withJson($body);
            break;
        case 'application/xml':
            # Building an XML with the data
            $newResponse = new SlimHttpResponse(); 
            return $newResponse->write($xml)->withHeader('Content-type', 'application/xml');
            break;
        case 'text/html':
            # Building a HTML list with the data
            $newResponse = new SlimHttpResponse(); 
            return $newResponse->write($list)->withHeader('Content-type', 'text/html;charset=utf-8');
            break;
    }
}

我有几条路线的行为类似:

$app->get('/api/users', 'UsersController:getUsers')->add($formatDataMiddleware);
$app->get('/api/products', 'UsersController:getProducts')->add($formatDataMiddleware);

通过使用中间件,我可以以声明性方式添加此类功能,从而使我的控制器保持精简。

如何将原始数据数组传递给响应并实现此模式?

Response -Object 不提供此功能,也有一些扩展来执行此操作。所以你需要调整响应类

class MyResponse extends SlimHttpResponse {
    private $data;
    public function getData() {
        return $this->data;
    }
    public function withData($data) {
        $clone = clone $this;
        $clone->data = $data;
        return $clone;
    }
}

然后,您需要将新的响应添加到容器中

$container = $app->getContainer();
$container['response'] = function($container) { // this stuff is the default from slim
    $headers = new Headers(['Content-Type' => 'text/html; charset=UTF-8']);
    $response = new MyResponse(200, $headers); // <-- adjust that to the new class
    return $response->withProtocolVersion($container->get('settings')['httpVersion']);
}

现在将响应类型更改为MyResponse并使用withData方法

public function getData(Request $request, MyResponse $response): Response {
    return $response->withData($this->getUsers());
}

最后,您可以使用 getData 方法并使用其值并在中间件中处理它。

public function __invoke(Request $request, MyResponse $response, callable $next) {
    $response = $next($request, $response);
    $data = $response->getData();
    // [..]
}

这将是你问题的答案。在我看来,更好的解决方案是一个帮助程序类,它执行中间件所做的事情,然后您可以像这样:

public function getData(Request $request, Response $response): Response {
    $data = $this->getUsers();        
    return $this->helper->formatOutput($request, $response, $data);
}

为此,已经有一个库:rka-content-type-renderer

最新更新