데이터가있는 배열을 미들웨어에 전달하고 Accept
HTTP 헤더를 기반으로 형식을 지정하려고합니다.
컨트롤러가 db에서 데이터를 가져 와서 응답 개체에 전달해야합니다.컨트롤러에서 미들웨어로 배열 전달 Slim 3 PHP
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 \Slim\Http\Response();
return $newResponse->write($xml)->withHeader('Content-type', 'application/xml');
break;
case 'text/html':
# Building a HTML list with the data
$newResponse = new \Slim\Http\Response();
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);
사용하여 응답 객체는 write()
메소드는 문자열을 받아 middlewares 내 컨트롤러를 얇게 유지하면서 선언적 방식으로 이러한 기능을 추가 할 수 있습니다.
원본 데이터 배열을 응답에 전달하고이 패턴을 구현하려면 어떻게해야합니까?
:
이를 위해 이미위한 lib 디렉토리가 내 의견에 더 나은 솔루션, 이런 일이 다음 수, 미들웨어가 무엇을 수행하는 도우미 클래스가 될 것입니다 check https://github.com/akrabat/rka-content-type-renderer –