minstudio

PSR-7과 PSR-15 인터페이스 이해

PHP 생태계에는 수많은 프레임워크가 있습니다. 옛날에는 서로 규격이 달라 부품이 호환되지 않았지만, PSR(PHP Standard Recommendation)이라는 표준 약속이 생겼습니다. Slim 프레임워크는 이 표준을 가장 완벽하게 지키는 모범생입니다.

🧩 PSR 표준 (레고 블록 규격)

라우터 A
미들웨어 B
로거 C
➡️
🔌
PSR 인터페이스 규격
- PSR-7 (HTTP 통신 규격)
- PSR-15 (미들웨어 규격)
➡️
🚀
Slim Framework

"규격만 맞으면
무엇이든 조립 가능!"

// PSR-15 규격을 정확히 지키는 미들웨어 클래스 예시
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class JsonBodyParserMiddleware implements MiddlewareInterface {
    
    // PSR-15는 반드시 process() 메서드를 구현하도록 강제합니다.
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        
        $contentType = $request->getHeaderLine('Content-Type');

        // JSON 데이터가 들어오면 자동으로 PHP 배열로 변환해서 Request 객체에 담아줌
        if (strstr($contentType, 'application/json')) {
            $contents = json_decode(file_get_contents('php://input'), true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $request = $request->withParsedBody($contents);
            }
        }

        // 다음 단계로 넘김
        return $handler->handle($request);
    }
}

// 클래스형 미들웨어 장착 (Slim은 PSR-15를 지원하므로 완벽하게 작동합니다)
$app->add(new JsonBodyParserMiddleware());
PSR-7과 PSR-15 인터페이스 이해 | Minstudio