
업그레이드 가이드
버전 3에서 버전 4로 업그레이드하는 경우 다음과 같은 중요한 변경 사항을 알고 있어야 합니다.
PHP 버전 요구 사항
슬림 4에는 PHP 7.2 이상 이 필요합니다.
Slim\App
생성자 변경
Slim의 앱 설정은 한때 컨테이너의 일부였지만 지금은 분리되었습니다.
/**
* Slim 3 App::__construct($container = [])
* As seen here the settings used to be nested
*/
$app = new App([
'settings' => [...],
]);
/**
* Slim 4 App::__constructor() method takes 1 mandatory parameter and 4 optional parameters
*
* @param ResponseFactoryInterface Any implementation of a ResponseFactory
* @param ContainerInterface|null Any implementation of a Container
* @param CallableResolverInterface|null Any implementation of a CallableResolver
* @param RouteCollectorInterface|null Any implementation of a RouteCollector
* @param RouteResolverInterface|null Any implementation of a RouteResolver
*/
$app = new App(...);
제거된 앱 설정
addContentLengthHeader
이 설정의 새로운 구현은 Content Length Middleware를 참조하십시오.determineRouteBeforeAppMiddleware
Routing Middleware를 미들웨어 스택의 올바른 위치에 배치하여 기존 동작을 복제합니다.outputBuffering
이 설정의 새로운 구현은 Output Buffering Middleware를 참조하십시오.displayErrorDetails
이 설정의 새로운 구현은 Error Handling Middleware를 참조하십시오.
컨테이너 변경사항
슬림은 더 이상 컨테이너가 없으므로 사용자는 사용자의 컨테이너를 공급해야 합니다. 컨테이너에 있는 요청이나 응답에 의존할 경우 직접 컨테이너로 설정하거나 refactor를 설정해야 합니다. 또한 App::__call()
메서드가 제거되었으므로 $app->key_name()
을 통해 컨테이너 속성에 액세스할 수 없습니다.
/**
* Slim 3.x shipped with the Pimple container implementation and enabled the following syntax
*/
$container = $app->getContainer();
//Assign dependencies as array
$container['view'] = function (\Psr\Container\ContainerInterface $container){
return new \Slim\Views\Twig('');
};
/**
* Slim 4.x does not ship with a container library. It supports all PSR-11 implementations such as PHP-DI
* To install PHP-DI `composer require php-di/php-di`
*/
use Slim\Factory\AppFactory;
$container = new \DI\Container();
AppFactory::setContainer($container);
$app = AppFactory::create();
$container = $app->getContainer();
$container->set('view', function(\Psr\Container\ContainerInterface $container){
return new \Slim\Views\Twig('');
});
기본 경로 처리의 변경 사항
v3까지 Slim은 애플리케이션이 인스턴스화된 폴더에서 기본 경로를 추출했다. 이것은 더 이상 해당되지 않으며 기본 경로는 명시적으로 선언되어야 합니다. 응용프로그램이 도메인의 루트에서 실행되지 않는 경우:
use Slim\Factory\AppFactory;
// ...
$app = AppFactory::create();
$app->setBasePath('/my-app-subpath');
// ...
$app->run();
라우팅 구성요소 변경사항
Slim3의 라우터 컴포넌트는 앱 코어에서 패스트루트를 분리해 최종 사용자에게 더 많은 유연성을 제공하기 위해 여러 가지 다른 컴포넌트로 분리됐다. RouteCollector
, RouteParser
,RouteResolver
로 나뉘었다. 이 3가지 구성 요소는 각자 인터페이스를 가질 수 있는데, 이 인터페이스는 당신이 직접 구현하여 앱 생성자에 주입할 수 있다. 다음 풀 요청은 이러한 새로운 구성요소의 공용 인터페이스에 대한 많은 정보를 제공합니다.
- Pull Request #2604
- Pull Request #2622
- Pull Request #2639
- Pull Request #2640
- Pull Request #2641
- Pull Request #2642
이는 Route Groups의 서명이 변경되었음을 의미하기도 합니다.
$app->group('/user', function(\Slim\Routing\RouteCollectorProxy $app){
$app->get('', function() { /* ... */ });
//...
});
새로운 미들웨어 접근 방식
Slim 4에서는 Slim의 앱 핵심 기능 일부를 분리하여 미들웨어로 구현함으로써 개발자들에게 더 많은 유연성을 주고 싶었습니다. 이를 통해 핵심 구성 요소의 사용자 지정 구현을 스왑할 수 있습니다.
미들웨어 실행
미들웨어 실행은 변하지 않고 슬림3처럼 LIFO(Last In First Out)다.
새 앱 팩토리
앱팩토리 컴포넌트는 PSR-7 구현체를 앱 코어에서 분리하면서 발생하는 마찰을 일부 줄이기 위해 도입됐다. 프로젝트 루트에 설치된 PSR-7 구현 및 ServerRequest Creator를 탐지하여 AppFactory::create()
를 통해 앱을 인스턴스화하고 ServerRequest
객체를 전달하지 않고도 App:run()
을 사용할 수 있습니다. 다음의 PSR-7 구현체 및 ServerRequest 작성자 조합이 지원됩니다.
새 라우팅 미들웨어
라우팅은 미들웨어로 구현되었습니다. 라우팅 요구에 대해서는 여전히 FastRoute를 사용하고 있습니다. determineRouteBeforeAppMiddleware
를 사용하는 경우 Middleware\RoutingMiddleware
를 추가해야 합니다.이전 동작을 유지하기 위해 ‘run()’을(를) 호출하기 직전에 미들웨어를 응용 프로그램에 라우팅합니다. 자세한 내용은 Pull Request #2288을 참조하십시오.
<?php
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// Add Routing Middleware
$app->addRoutingMiddleware();
// ...
$app->run();
새 오류 처리 미들웨어
미들웨어로도 에러 처리가 구현됐다. 자세한 내용은 Pull Request #2398을 참조하십시오.
<?php
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
/**
* The routing middleware should be added before the ErrorMiddleware
* Otherwise exceptions thrown from it will not be handled
*/
$app->addRoutingMiddleware();
/**
* Add Error Handling Middleware
*
* @param bool $displayErrorDetails -> Should be set to false in production
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler
* @param bool $logErrorDetails -> Display error details in error log
* which can be replaced by a callable of your choice.
* Note: This middleware should be added last. It will not handle any exceptions/errors
* for middleware added after it.
*/
$app->addErrorMiddleware(true, true, true);
// ...
$app->run();
New Not Found and Not Allowed Handler
v3에서 404 Not Found Handler 및 405 Not Allowed Handler를 다음과 같이 마이그레이션할 수 있습니다.
<?php
use Psr\Http\Message\ServerRequestInterface;
use Slim\Factory\AppFactory;
use Slim\Exception\HttpNotFoundException;
use Slim\Exception\HttpMethodNotAllowedException;
use Slim\Psr7\Response;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
// Set the Not Found Handler
$errorMiddleware->setErrorHandler(
HttpNotFoundException::class,
function (ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails) {
$response = new Response();
$response->getBody()->write('404 NOT FOUND');
return $response->withStatus(404);
});
// Set the Not Allowed Handler
$errorMiddleware->setErrorHandler(
HttpMethodNotAllowedException::class,
function (ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails) {
$response = new Response();
$response->getBody()->write('405 NOT ALLOWED');
return $response->withStatus(405);
});
새로운 디스패처 & 라우팅 결과
FastRoute 디스패처 주위에 래퍼를 만들어 예외가 발생하는 경우에만 액세스할 수 있는 대신 결과 래퍼와 라우트의 허용된 메소드 전체 목록에 액세스 권한을 추가했다. 요청 특성 ‘routeInfo’는 이제 사용되지 않으며 ‘routingResults’로 대체됩니다. 자세한 내용은 Pull Request #2405를 참조하십시오.
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Routing\RouteContext;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->get('/hello/{name}', function (Request $request, Response $response) {
$routeContext = RouteContext::fromRequest($request);
$routingResults = $routeContext->getRoutingResults();
// Get all of the route's parsed arguments e.g. ['name' => 'John']
$routeArguments = $routingResults->getRouteArguments();
// A route's allowed methods are available at all times now and not only when an error arises like in Slim 3
$allowedMethods = $routingResults->getAllowedMethods();
return $response;
});
// ...
$app->run();
미들웨어를 재정의하는 새 메서드
사용자 지정 헤더 또는 본문 매개 변수를 사용하여 HTTP 메서드를 재정의하는 경우 ‘Middleware’를 추가해야 합니다.MethodOverride 미들웨어는 이전과 같이 MethodOverride Middleware를 재정의할 수 있게 되었습니다. 자세한 내용은 Pull Request #2329를 참조하십시오.
<?php
use Slim\Factory\AppFactory;
use Slim\Middleware\MethodOverridingMiddleware;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$methodOverridingMiddleware = new MethodOverrideMiddleware();
$app->add($methodOverridingMiddleware);
// ...
$app->run();
새 콘텐츠 길이 미들웨어
Content Length 미들웨어는 응답에 Content-Length 헤더를 자동으로 추가합니다. 슬림3에서 삭제됐던 addContentLengthHeader 설정을 대체하기 위해서다. 이 미들웨어는 미들웨어 스택 중앙에 위치해야 마지막에 실행됩니다.
<?php
use Slim\Factory\AppFactory;
use Slim\Middleware\ContentLengthMiddleware;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$contentLengthMiddleware = new ContentLengthMiddleware();
$app->add($contentLengthMiddleware);
// ...
$app->run();
새 출력 버퍼링 미들웨어
Output Buffering Middleware를 사용하면 두 가지 출력 버퍼링 모드인 ‘APPEND'(기본값)와 ‘PREPEND’ 모드 사이에서 전환할 수 있습니다. APPEND 모드는 기존 응답 본문을 사용하여 내용을 추가하는 반면, PREPEND 모드는 새 응답 본문을 만들어 기존 응답에 추가합니다. 이 미들웨어는 미들웨어 스택 중앙에 위치해야 마지막에 실행됩니다.
<?php
use Slim\Factory\AppFactory;
use Slim\Middleware\OutputBufferingMiddleware;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
/**
* The two modes available are
* OutputBufferingMiddleware::APPEND (default mode) - Appends to existing response body
* OutputBufferingMiddleware::PREPEND - Creates entirely new response body
*/
$mode = OutputBufferingMiddleware::APPEND;
$outputBufferingMiddleware = new OutputBufferingMiddleware($mode);
// ...
$app->run();