### Complete Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RouteCollectorProxy.md A comprehensive example showcasing the setup of a Slim application, including main routes, API versioning with groups, resource routing, middleware application, and redirects. ```APIDOC ## Complete Example ```php use Slim actory actory; $app = factory::create(); // Main routes $app->get('/', $homeHandler); $app->post('/contact', $submitContactHandler); // API v1 $app->group('/api/v1', function($api) { // Users resource $api->group('/users', function($users) { $users->get('', $listHandler)->setName('listUsers'); $users->post('', $createHandler)->setName('createUser'); $users->get('/{id}', $getHandler)->setName('getUser'); $users->put('/{id}', $updateHandler)->setName('updateUser'); $users->delete('/{id}', $deleteHandler)->setName('deleteUser'); })->add(AuthMiddleware::class); })->add(ApiResponseMiddleware::class); // Redirects $app->redirect('/old-docs', '/docs', 301); $app->run(); ``` ``` -------------------------------- ### Complete Slim Framework Configuration Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/configuration.md A comprehensive example demonstrating the setup of a Slim Framework application. It includes container configuration, middleware addition, error handling, and route registration. ```php use Slim\Factory\AppFactory; use Slim\Middleware\OutputBufferingMiddleware; use Slim\Middleware\ContentLengthMiddleware; use Slim\Middleware\MethodOverrideMiddleware; use Slim\Exception\HttpNotFoundException; use DI\Container; use Monolog\Logger; use Monolog\Handlers\StreamHandler; // Create container $container = new Container(); // Register services $container->set('logger', function() { $logger = new Logger('app'); $logger->pushHandler(new StreamHandler('php://stderr')); return $logger; }); $container->set('userRepository', function() { return new UserRepository(/* ... */); }); // Configure AppFactory AppFactory::setContainer($container); // Create application $app = AppFactory::create(); // Set base path $app->setBasePath('/api/v1'); // Add middleware (in reverse execution order) $app->add(new ContentLengthMiddleware()); // Last $app->add(new MethodOverrideMiddleware()); // Middle $app->add(new OutputBufferingMiddleware()); // Early // Add built-in middleware $app->addErrorMiddleware( displayErrorDetails: true, logErrors: true, logErrorDetails: true, logger: $container->get('logger') ); $app->addRoutingMiddleware(); $app->addBodyParsingMiddleware(); // Configure error handlers $errorMiddleware = $app->addErrorMiddleware(true, true, true); $errorMiddleware->setErrorHandler( HttpNotFoundException::class, function($request, $exception) { $response = /* create response */; $response->getBody()->write(json_encode([ 'error' => 'Not Found', 'status' => 404 ])); return $response ->withStatus(404) ->withHeader('Content-Type', 'application/json'); } ); // Register routes $app->get('/users', 'UserController:list'); $app->post('/users', 'UserController:create'); $app->get('/users/{id}', 'UserController:show'); $app->run(); ``` -------------------------------- ### Complete Slim Application Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RouteCollectorProxy.md A comprehensive example demonstrating Slim application setup, including route registration for main routes, API groups with nested resources, middleware application, and redirects. The application is then run. ```php use Slim\Factory\AppFactory; $app = AppFactory::create(); // Main routes $app->get('/', $homeHandler); $app->post('/contact', $submitContactHandler); // API v1 $app->group('/api/v1', function($api) { // Users resource $api->group('/users', function($users) { $users->get('', $listHandler)->setName('listUsers'); $users->post('', $createHandler)->setName('createUser'); $users->get('/{id}', $getHandler)->setName('getUser'); $users->put('/{id}', $updateHandler)->setName('updateUser'); $users->delete('/{id}', $deleteHandler)->setName('deleteUser'); })->add(AuthMiddleware::class); })->add(ApiResponseMiddleware::class); // Redirects $app->redirect('/old-docs', '/docs', 301); $app->run(); ``` -------------------------------- ### Complete Error Setup Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ErrorMiddleware.md Demonstrates how to configure Slim's error middleware with custom handlers for specific HTTP exceptions like 404 Not Found and validation errors. This setup includes enabling error details and logging. ```php use Slim\Factory\AppFactory; use Slim\Exception\HttpNotFoundException; use Slim\Exception\HttpInternalServerErrorException; $app = AppFactory::create(); $errorMiddleware = $app->addErrorMiddleware( displayErrorDetails: true, logErrors: true, logErrorDetails: true, logger: $logger ); // Custom 404 handler $errorMiddleware->setErrorHandler( HttpNotFoundException::class, function($request, $exception) use ($responseFactory) { $response = $responseFactory->createResponse(404); $response->getBody()->write('{"error": "Not Found"}'); return $response->withHeader('Content-Type', 'application/json'); } ); // Custom validation error handler $errorMiddleware->setErrorHandler( ValidationException::class, function($request, $exception) use ($responseFactory) { $response = $responseFactory->createResponse(422); $response->getBody()->write(json_encode([ 'error' => 'Validation Failed', 'messages' => $exception->getErrors() ])); return $response->withHeader('Content-Type', 'application/json'); } ); $app->run(); ``` -------------------------------- ### Typical Slim Application Setup with ContentLengthMiddleware Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ContentLengthMiddleware.md A comprehensive example of setting up a Slim application, including error handling, routing, body parsing, and the ContentLengthMiddleware. This demonstrates a common application structure. ```php use Slim\Factory\AppFactory; use Slim\Middleware\ContentLengthMiddleware; use Slim\Middleware\BodyParsingMiddleware; use Slim\Middleware\ErrorMiddleware; $app = AppFactory::create(); // Error handling $app->addErrorMiddleware( displayErrorDetails: true, logErrors: true, logErrorDetails: true ); // Routing and body parsing $app->addRoutingMiddleware(); $app->addBodyParsingMiddleware(); // Content-Length header management $app->add(new ContentLengthMiddleware()); // API endpoints $app->get('/api/users', function($request, $response) { $response->getBody()->write(json_encode(['users' => []])); return $response->withHeader('Content-Type', 'application/json'); }); $app->run(); ``` -------------------------------- ### Hello World Example with PSR-7 Auto-Detection Source: https://github.com/slimphp/slim/blob/4.x/README.md A basic 'Hello World' Slim application that utilizes AppFactory for PSR-7 auto-detection. Ensure a PSR-7 implementation is installed. ```php addErrorMiddleware(true, true, true); // Add routes $app->get('/', function (Request $request, Response $response) { $response->getBody()->write('Try /hello/world'); return $response; }); $app->get('/hello/{name}', function (Request $request, Response $response, $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; }); $app->run(); ``` -------------------------------- ### Minimal Slim 5 Application Example Source: https://github.com/slimphp/slim/wiki/Slim-5-Road-Map A basic Slim 5 application setup including middleware registration and route definition. Ensure all required middleware is added before running the application. ```php add(RoutingMiddleware::class); $app->add(BodyParsingMiddleware::class); $app->add(ExceptionHandlingMiddleware::class); $app->add(ExceptionLoggingMiddleware::class); $app->add(EndpointMiddleware::class); // Register Routes $app->get('/', function ($request, $response, $args) { $response->getBody()->write("Hello, World!"); return $response; }); // Register route with action class $app->get('/ping', \App\Action\PingAction::class); // Run the app $app->run(); ``` -------------------------------- ### Complete SlimPHP Application with OutputBufferingMiddleware Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/OutputBufferingMiddleware.md A full example demonstrating the setup and usage of OutputBufferingMiddleware in a SlimPHP application. ```php use Slim\Factory\AppFactory; use Slim\Middleware\OutputBufferingMiddleware; $app = AppFactory::create(); // Add output buffering middleware $app->add(new OutputBufferingMiddleware('APPEND')); $app->get('/test', function($request, $response) { // This echo is normally bad practice but captured echo "Debug output\n"; $response->getBody()->write('Actual response'); return $response->withHeader('Content-Type', 'text/plain'); }); // Response body will contain: // "Actual response" + captured "Debug output" $app->run(); ``` -------------------------------- ### Complete Application Example with MethodOverrideMiddleware Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/MethodOverrideMiddleware.md This example demonstrates how to integrate MethodOverrideMiddleware and BodyParsingMiddleware into a Slim application. It shows how to handle GET, PUT, and DELETE requests, allowing them to be triggered via forms or AJAX requests that utilize the `_METHOD` parameter or an override header. ```php use Slim\Factory\AppFactory; use Slim\Middleware\MethodOverrideMiddleware; use Slim\Middleware\BodyParsingMiddleware; $app = AppFactory::create(); // Add middleware in order $app->add(new MethodOverrideMiddleware()); // Allow method override $app->add(new BodyParsingMiddleware()); // Parse request body // GET - Show edit form $app->get('/users/{id}/edit', function($request, $response, $args) { $user = getUser($args['id']); return renderEditForm($response, $user); }); // PUT - Update user (from AJAX with header or form with _METHOD) $app->put('/users/{id}', function($request, $response, $args) { $data = $request->getParsedBody(); $user = getUser($args['id']); updateUser($user, $data); return $response ->withStatus(200) ->withHeader('Content-Type', 'application/json'); }); // DELETE - Delete user (from AJAX with header or form with _METHOD) $app->delete('/users/{id}', function($request, $response, $args) { deleteUser($args['id']); return $response ->withStatus(204); // No Content }); $app->run(); ``` -------------------------------- ### Complete CallableResolver Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/CallableResolver.md Illustrates the setup and usage of CallableResolver within a Slim application. It shows how to create a resolver with a container, set up services, and define routes using various callable notations including middleware classes, Slim notation, array notation, and closures. ```php use Slim\Factory\AppFactory; use Slim\CallableResolver; use MyApp\Middleware\AuthMiddleware; use MyApp\Handlers\UserController; // Create resolver with container $container = new Container(); $resolver = new CallableResolver($container); // Set up services $container->set(UserController::class, fn() => new UserController( $container->get(UserRepository::class) )); // Create app $app = AppFactory::create(); // Use various callable notations $app->add(AuthMiddleware::class); // Middleware class $app->get('/users', 'UserController:list'); // Slim notation $app->get('/users/{id}', [UserController::class, 'show']); // Array notation $app->post('/users', function($req, $res) { // Closure return $res; }); $app->run(); ``` -------------------------------- ### Complete Example: Creating and Using a Server Request Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ServerRequestCreatorFactory.md A comprehensive example demonstrating how to obtain the creator, create a request from globals, and understand the properties populated in the request. ```APIDOC ## Complete Example ```php use Slim\Factory\ServerRequestCreatorFactory; // Get the server request creator $serverRequestCreator = ServerRequestCreatorFactory::create(); // Create a request from current PHP superglobals ($_SERVER, $_GET, $_POST, etc.) $request = $serverRequestCreator->createServerRequestFromGlobals(); // Request now contains: // - Method: $_SERVER['REQUEST_METHOD'] // - URI: $_SERVER['HTTP_HOST'] + $_SERVER['REQUEST_URI'] // - Headers: $_SERVER['HTTP_*'] headers // - Query: $_GET // - Body: php://input // - Uploaded Files: $_FILES ``` ## Request Properties Created The created request contains: | Property | Source | |----------|--------| | Method | `$_SERVER['REQUEST_METHOD']` | | URI | `$_SERVER['HTTP_HOST']`, etc. | | Query Parameters | `$_GET` | | Body | `php://input` | | Headers | `$_SERVER['HTTP_*']` | | Uploaded Files | `$_FILES` | | Protocol Version | `$_SERVER['SERVER_PROTOCOL']` | | Server Params | `$_SERVER` | ``` -------------------------------- ### Complete REST API Example with Slim Framework Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/endpoints.md This snippet shows a full implementation of a REST API for user management. It includes routes for listing, creating, retrieving, updating, and deleting users. It also demonstrates the use of middleware for error handling, routing, and body parsing. Ensure you have the Slim Framework and its dependencies installed. ```php use Slim\Factory\AppFactory; use Slim\Exception\HttpNotFoundException; use Slim\Exception\HttpBadRequestException; $app = AppFactory::create(); $app->addErrorMiddleware(true, true, true); $app->addRoutingMiddleware(); $app->addBodyParsingMiddleware(); // GET /api/users - List all users $app->get('/api/users', function($request, $response) { $users = getUsersRepository()->findAll(); $response->getBody()->write(json_encode(['data' => $users])); return $response ->withHeader('Content-Type', 'application/json') ->withStatus(200); }); // POST /api/users - Create user $app->post('/api/users', function($request, $response) { $data = $request->getParsedBody(); if (!isset($data['name']) || !isset($data['email'])) { throw new HttpBadRequestException($request, 'Missing required fields'); } $user = getUsersRepository()->create($data); $response->getBody()->write(json_encode($user)); return $response ->withHeader('Content-Type', 'application/json') ->withStatus(201) ->withHeader('Location', "/api/users/{$user['id']}"); }); // GET /api/users/{id} - Get user $app->get('/api/users/{id}', function($request, $response, $args) { $user = getUsersRepository()->findById($args['id']); if (!$user) { throw new HttpNotFoundException($request, 'User not found'); } $response->getBody()->write(json_encode($user)); return $response ->withHeader('Content-Type', 'application/json') ->withStatus(200); }); // PUT /api/users/{id} - Update user $app->put('/api/users/{id}', function($request, $response, $args) { $user = getUsersRepository()->findById($args['id']); if (!$user) { throw new HttpNotFoundException($request, 'User not found'); } $data = $request->getParsedBody(); $updated = getUsersRepository()->update($args['id'], $data); $response->getBody()->write(json_encode($updated)); return $response ->withHeader('Content-Type', 'application/json') ->withStatus(200); }); // DELETE /api/users/{id} - Delete user $app->delete('/api/users/{id}', function($request, $response, $args) { $user = getUsersRepository()->findById($args['id']); if (!$user) { throw new HttpNotFoundException($request, 'User not found'); } getUsersRepository()->delete($args['id']); return $response->withStatus(204); }); $app->run(); ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/slimphp/slim/blob/4.x/README.md Clone the repository, install development dependencies using Composer, and execute the test suite. ```bash git clone https://github.com/slimphp/Slim composer install composer test ``` -------------------------------- ### Complete MiddlewareDispatcher Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/MiddlewareDispatcher.md This example shows how to set up a RouteKernel, define custom middleware (Logging, Auth, Cors), and add them to the MiddlewareDispatcher. Middleware is added in reverse execution order, meaning the first middleware added executes last. ```php use Slim\MiddlewareDispatcher; use Slim\CallableResolver; use Psr\Http\Server\RequestHandlerInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; // Mock kernel (route handler) class RouteKernel implements RequestHandlerInterface { public function handle(ServerRequestInterface $request): ResponseInterface { // Handle the route $response = /* create response */; return $response; } } // Middleware 1: Logging class LoggingMiddleware { public function __invoke($request, $handler) { echo "Start request: " . $request->getMethod() . " " . $request->getUri()->getPath(); $response = $handler->handle($request); echo "End request with status " . $response->getStatusCode(); return $response; } } // Middleware 2: Authentication class AuthMiddleware { public function __invoke($request, $handler) { if (!$request->hasHeader('Authorization')) { throw new HttpUnauthorizedException($request); } return $handler->handle($request); } } // Middleware 3: CORS class CorsMiddleware { public function __invoke($request, $handler) { $response = $handler->handle($request); return $response ->withHeader('Access-Control-Allow-Origin', '*') ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); } } // Set up dispatcher $kernel = new RouteKernel(); $resolver = new CallableResolver(); $dispatcher = new MiddlewareDispatcher($kernel, $resolver); // Add middleware (in reverse execution order) $dispatcher->add(LoggingMiddleware::class); // Executes 3rd $dispatcher->add(AuthMiddleware::class); // Executes 2nd $dispatcher->add(CorsMiddleware::class); // Executes 1st // Process request $response = $dispatcher->handle($request); // Execution flow: // 1. CorsMiddleware starts // 2. AuthMiddleware starts // 3. LoggingMiddleware starts // 4. RouteKernel handles // 5. LoggingMiddleware ends // 6. AuthMiddleware ends // 7. CorsMiddleware ends ``` -------------------------------- ### Install Slim 5 and Dependencies Source: https://github.com/slimphp/slim/wiki/Slim-5-Road-Map Use Composer to install Slim 5, PSR-7, and a PSR-11 compatible DI container like php-di. ```bash composer require slim/slim:5.* composer require slim/psr7 composer require php-di/php-di ``` -------------------------------- ### Install Slim-Http Source: https://github.com/slimphp/slim/blob/4.x/README.md Install the Slim-Http library using Composer. This library provides decorators for PSR-7 implementations. ```bash composer require slim/http ``` -------------------------------- ### Static Route Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RouteCollectorProxy.md Demonstrates the basic syntax for defining static routes that match an exact URI. ```php $app->get('/about', $handler); $app->get('/contact', $handler); ``` -------------------------------- ### Install Slim Framework with Composer Source: https://github.com/slimphp/slim/blob/4.x/README.md Use Composer to install Slim and its dependencies. Requires PHP 7.4 or newer. ```bash composer require slim/slim ``` -------------------------------- ### Complete Example of Server Request Creation Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ServerRequestCreatorFactory.md This example demonstrates how to obtain a ServerRequestCreatorInterface and use it to create a ServerRequestInterface from the current PHP superglobals. The resulting request object will contain details like method, URI, headers, query parameters, and body. ```php use Slim\Factory\ServerRequestCreatorFactory; // Get the server request creator $serverRequestCreator = ServerRequestCreatorFactory::create(); // Create a request from current PHP superglobals ($_SERVER, $_GET, $_POST, etc.) $request = $serverRequestCreator->createServerRequestFromGlobals(); // Request now contains: // - Method: $_SERVER['REQUEST_METHOD'] // - URI: $_SERVER['HTTP_HOST'] + $_SERVER['REQUEST_URI'] // - Headers: $_SERVER['HTTP_*'] headers // - Query: $_GET // - Body: php://input // - Uploaded Files: $_FILES ``` -------------------------------- ### Registering a GET Route Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RouteCollectorProxy.md Use the `get` method to register a route that responds to GET requests. The handler is a callable that receives the request and response objects. ```php $app->get('/users', function($request, $response) { $response->getBody()->write('List users'); return $response; }); ``` -------------------------------- ### Example Response Headers Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ResponseEmitter.md An example of HTTP response headers that the ResponseEmitter sends. ```http Content-Type: application/json Content-Length: 256 Cache-Control: no-cache ``` -------------------------------- ### URL Generation Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/types.md Demonstrates how to generate a relative URL for a named route using route parameters. ```php $url = $routeParser->relativeUrlFor('userDetail', ['id' => 123]); // Returns: /users/123 ``` -------------------------------- ### Manual Request Creation for Testing with GuzzleHttp Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ServerRequestCreatorFactory.md This example demonstrates creating different types of `ServerRequest` objects manually using GuzzleHttp's PSR-7 implementation, including a GET request and a POST request with a JSON body. These are useful for testing application logic without relying on superglobals. ```php use Slim\Factory\AppFactory; use GuzzleHttp\Psr7\ServerRequest; use GuzzleHttp\Psr7\Uri; $app = AppFactory::create(); // Create a GET request $request = new ServerRequest('GET', new Uri('http://localhost/users')); // Create a POST request with JSON body $request = new ServerRequest( 'POST', new Uri('http://localhost/users'), ['Content-Type' => 'application/json'], json_encode(['name' => 'John']) ); // Handle the request $response = $app->handle($request); // Check response echo $response->getStatusCode(); // 201 ``` -------------------------------- ### HTML Response Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ContentLengthMiddleware.md Illustrates the ContentLengthMiddleware's behavior with an HTML response, where it automatically calculates and sets the Content-Length header. ```php $app->add(new ContentLengthMiddleware()); $app->get('/page', function($request, $response) { $html = 'Hello World'; $response->getBody()->write($html); return $response ->withHeader('Content-Type', 'text/html'); // Content-Length is automatically calculated }); ``` -------------------------------- ### Typical Slim Application Flow with ResponseEmitter Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ResponseEmitter.md This example illustrates the standard flow of a Slim Framework application, from creating the app and registering routes to running the application, where the ResponseEmitter is implicitly called to send the final response. ```php use Slim\Factory\AppFactory; use Slim\ResponseEmitter; use Psr\Http\Message\ResponseInterface; $app = AppFactory::create(); // Register routes $app->get('/users', function($request, $response) { $response->getBody()->write(json_encode(['users' => []])); return $response->withHeader('Content-Type', 'application/json'); }); // When app->run() is called: // 1. Request is created from globals // 2. Request is handled through middleware // 3. Response is returned // 4. ResponseEmitter::emit() is called // 5. Response is sent to client $app->run(); ``` -------------------------------- ### Security Considerations with MethodOverrideMiddleware Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/MethodOverrideMiddleware.md This example integrates MethodOverrideMiddleware and BodyParsingMiddleware while also incorporating security best practices. It includes checks for authentication and logs actions before performing a delete operation, demonstrating a more robust implementation for sensitive operations. ```php $app->add(new MethodOverrideMiddleware()); $app->add(new BodyParsingMiddleware()); $app->delete('/users/{id}', function($request, $response, $args) { // Check authentication if (!isAuthenticated($request)) { throw new HttpUnauthorizedException($request); } // Log the action logAction('delete_user', $args['id'], getUser($request)); // Perform deletion deleteUser($args['id']); return $response->withStatus(204); })->add(AuthMiddleware::class); ``` -------------------------------- ### Output Buffering Modes Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/OutputBufferingMiddleware.md Explains the 'APPEND' and 'PREPEND' modes for the OutputBufferingMiddleware, detailing their behavior and providing usage examples. ```APIDOC ## Output Buffering Modes ### APPEND Mode Appends any buffered output to the response body: ```php $app->add(new OutputBufferingMiddleware('APPEND')); ``` **Flow:** 1. Start output buffering 2. Execute handler 3. Capture buffered output 4. Append to response body 5. Flush buffer ### PREPEND Mode Prepends any buffered output to the response body: ```php $app->add(new OutputBufferingMiddleware('PREPEND')); ``` **Flow:** 1. Start output buffering 2. Execute handler 3. Capture buffered output 4. Prepend to response body 5. Flush buffer ``` -------------------------------- ### Registering a Route for All HTTP Methods Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RouteCollectorProxy.md Use the `any` method to register a route that responds to any HTTP method (GET, POST, PUT, PATCH, DELETE, OPTIONS). The handler is provided as the second argument. ```php $app->any('/api/endpoint', $handler); ``` -------------------------------- ### Register Custom YAML and CSV Parsers Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/BodyParsingMiddleware.md This example shows how to extend the BodyParsingMiddleware by registering custom parsers for 'application/x-yaml' and 'text/csv'. This allows handling non-standard content types. ```php use Slim\Factory\AppFactory; use Slim\Middleware\BodyParsingMiddleware; $app = AppFactory::create(); // Create custom body parsing middleware $bodyParsingMiddleware = new BodyParsingMiddleware(); // Add custom YAML parser $bodyParsingMiddleware->registerBodyParser( 'application/x-yaml', function($body) { // Use a YAML library like symfony/yaml return Yaml::parse((string)$body); } ); // Add custom CSV parser $bodyParsingMiddleware->registerBodyParser( 'text/csv', function($body) { $lines = explode("\n", (string)$body); $headers = str_getcsv(array_shift($lines)); $data = array_map( fn($line) => array_combine($headers, str_getcsv($line)), $lines ); return $data; } ); $app->add($bodyParsingMiddleware); $app->post('/api/yaml', function($request, $response) { $data = $request->getParsedBody(); return $response; }); $app->run(); ``` -------------------------------- ### Testing Without Superglobals: Manual Request Creation Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ServerRequestCreatorFactory.md Provides examples of how to manually create `ServerRequestInterface` instances for testing purposes, bypassing the need for actual superglobals. ```APIDOC ## Testing Without Superglobals In tests, create requests manually: ```php use PHPUnit\Framework\TestCase; use GuzzleHttp\Psr7\ServerRequest; class RouteTest extends TestCase { public function testGetRoute() { $app = AppFactory::create(); $app->get('/users', function($request, $response) { return $response; }); // Create request manually for testing $request = new ServerRequest('GET', '/users'); $response = $app->handle($request); $this->assertEquals(200, $response->getStatusCode()); } } ``` ## Manual Request Creation for Testing ```php use Slim\Factory\AppFactory; use GuzzleHttp\Psr7\ServerRequest; use GuzzleHttp\Psr7\Uri; $app = AppFactory::create(); // Create a GET request $request = new ServerRequest('GET', new Uri('http://localhost/users')); // Create a POST request with JSON body $request = new ServerRequest( 'POST', new Uri('http://localhost/users'), ['Content-Type' => 'application/json'], json_encode(['name' => 'John']) ); // Handle the request $response = $app->handle($request); // Check response echo $response->getStatusCode(); // 201 ``` ``` -------------------------------- ### Testing with Manually Created Request Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ServerRequestCreatorFactory.md In test environments, it's common to bypass superglobals and create requests manually. This example shows how to create a `ServerRequest` using GuzzleHttp's implementation for testing a route. ```php use PHPUnit\Framework\TestCase; use GuzzleHttp\Psr7\ServerRequest; class RouteTest extends TestCase { public function testGetRoute() { $app = AppFactory::create(); $app->get('/users', function($request, $response) { return $response; }); // Create request manually for testing $request = new ServerRequest('GET', '/users'); $response = $app->handle($request); $this->assertEquals(200, $response->getStatusCode()); } } ``` -------------------------------- ### Handle PUT requests with X-HTTP-Method-Override Header Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/MethodOverrideMiddleware.md This example shows how to configure a PUT route that can be invoked by a POST request with the X-HTTP-Method-Override header set to PUT. This is the recommended method for overriding HTTP verbs. ```http POST /users HTTP/1.1 X-HTTP-Method-Override: PUT {...} ``` ```php $app->add(new MethodOverrideMiddleware()); $app->put('/users/{id}', function($request, $response, $args) { // Handles PUT requests and POST with X-HTTP-Method-Override: PUT return $response; }); ``` -------------------------------- ### Handling Headers Already Sent Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ResponseEmitter.md The emitter respects PHP's restrictions on sending headers. If headers have already been sent, it will not attempt to send them again, preventing errors. This example shows a safe emission before headers are sent and a subsequent emission after output has started. ```php // Safe - headers not sent yet $emitter->emit($response); // After response sent, headers cannot be modified echo "Output"; $emitter->emit($response2); // This won't send headers again ``` -------------------------------- ### Create a Slim Application Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/README.md Instantiate the Slim application using AppFactory. This is the entry point for your application. ```php use Slim\Factory\AppFactory; $app = AppFactory::create(); $app->get('/', function($request, $response) { $response->getBody()->write('Hello, World!'); return $response; }); $app->run(); ``` -------------------------------- ### Example Status Line Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ResponseEmitter.md An example of an HTTP status line that the ResponseEmitter sets. ```http HTTP/1.1 200 OK ``` -------------------------------- ### GET Endpoint Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/endpoints.md Register a route that responds to GET requests to retrieve a list of users. ```APIDOC ## GET /users ### Description Retrieves a list of users. ### Method GET ### Endpoint /users ### Response #### Success Response (200) - users (JSON array) - A JSON array containing user objects. ### Response Example { "users": [ // ... user objects ] } ``` -------------------------------- ### Typical Application Flow with Automatic Request Handling Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ServerRequestCreatorFactory.md This snippet shows the recommended way to run a Slim application, where the request is automatically created from superglobals when `$app->run()` is called. It also includes an alternative manual handling approach. ```php use Slim\Factory\AppFactory; use Slim\Factory\ServerRequestCreatorFactory; $app = AppFactory::create(); // Register routes $app->get('/users', function($request, $response) { // Request is already created from globals return $response; }); // Option 1: Automatic handling (recommended) $app->run(); // Internally creates request from globals // Option 2: Manual handling $serverRequestCreator = ServerRequestCreatorFactory::create(); $request = $serverRequestCreator->createServerRequestFromGlobals(); $response = $app->handle($request); $emitter = new ResponseEmitter(); $emitter->emit($response); ``` -------------------------------- ### Initialize Middleware with PREPEND Mode Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/OutputBufferingMiddleware.md Adds the OutputBufferingMiddleware to the application with the 'PREPEND' mode. ```php $app->add(new OutputBufferingMiddleware('PREPEND')); ``` -------------------------------- ### Get Routing Results Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RoutingMiddleware.md Access the RoutingResults object from request attributes to get routing status and arguments. This object contains details about the routing outcome. ```php $routingResults = $request->getAttribute(RouteContext::ROUTING_RESULTS); $status = $routingResults->getRouteStatus(); $arguments = $routingResults->getRouteArguments(); ``` -------------------------------- ### Create Slim App Instance Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/AppFactory.md Use this method to create a new Slim application instance. It automatically detects PSR-17 implementations if not provided. ```php use Slim\Factory\AppFactory; $app = AppFactory::create(); $app->get('/', function($request, $response) { $response->getBody()->write('Hello World'); return $response; }); $app->run(); ``` -------------------------------- ### Register GET Endpoint for Users Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/endpoints.md Use this to register a route that responds to GET requests for fetching user data. It returns a JSON array of users and sets the Content-Type header. ```php $app->get('/users', function($request, $response) { $response->getBody()->write(json_encode(['users' => [...]])); return $response->withHeader('Content-Type', 'application/json'); }); ``` -------------------------------- ### create Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/AppFactory.md Creates an App instance with automatic PSR-17 implementation detection. You can optionally provide custom implementations for various components. ```APIDOC ## create ### Description Create an `App` instance with automatic PSR-17 implementation detection. ### Method `public static function create( ?ResponseFactoryInterface $responseFactory = null, ?ContainerInterface $container = null, ?CallableResolverInterface $callableResolver = null, ?RouteCollectorInterface $routeCollector = null, ?RouteResolverInterface $routeResolver = null, ?MiddlewareDispatcherInterface $middlewareDispatcher = null ): App ``` ```APIDOC ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **responseFactory** (`ResponseFactoryInterface | null`) - Optional - Custom PSR-17 response factory; auto-detected if omitted - **container** (`ContainerInterface | null`) - Optional - PSR-11 service container - **callableResolver** (`CallableResolverInterface | null`) - Optional - Custom callable resolver - **routeCollector** (`RouteCollectorInterface | null`) - Optional - Custom route collector - **routeResolver** (`RouteResolverInterface | null`) - Optional - Custom route resolver - **middlewareDispatcher** (`MiddlewareDispatcherInterface | null`) - Optional - Custom middleware dispatcher ### Returns `App` — The created application instance ### Throws `RuntimeException` — If no PSR-17 implementation is detected ### Example ```php use Slim\Factory\AppFactory; $app = AppFactory::create(); $app->get('/', function($request, $response) { $response->getBody()->write('Hello World'); return $response; }); $app->run(); ``` ``` -------------------------------- ### Set Default Error Handler Example Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ErrorMiddleware.md This example shows how to set a custom default error handler for the ErrorMiddleware. The handler is a closure that accepts request, exception, and error detail parameters, returning a PSR-7 ResponseInterface. ```php $errorMiddleware = $app->addErrorMiddleware(true, true, true); $errorMiddleware->setDefaultErrorHandler(function( $request, $exception, $displayErrorDetails, $logErrors, $logErrorDetails ) { // Custom error handling return createCustomErrorResponse($exception); }); ``` -------------------------------- ### Method Chaining Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RouteCollectorProxy.md Demonstrates how route registration methods return route instances, enabling method chaining for setting route names and adding middleware. ```APIDOC ## Method Chaining All route registration methods return the route instance for chaining: ```php $app->get('/users', $handler) ->setName('listUsers') ->add(AuthMiddleware::class); $app->group('/api', $callback) ->add(CorsMiddleware::class); ``` ``` -------------------------------- ### Best Practices: Logical Grouping Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RouteGroup.md Demonstrates organizing routes logically with clear middleware responsibilities for better maintainability. ```php // Good: Logical grouping with clear middleware responsibilities $app->group('/api', function($api) { $api->group('/users', function($users) { $users->get('', $list); $users->post('', $create); $users->get('/{id}', $show); })->add(ValidateUserInput::class); $api->group('/posts', function($posts) { $posts->get('', $list); $posts->post('', $create); })->add(ValidatePostInput::class); }) ->add(AuthMiddleware::class) ->add(CorsMiddleware::class); // Avoid: Too many deeply nested groups // $app->group(...)->group(...)->group(...)->group(...) // Too deep! ``` -------------------------------- ### OPTIONS Endpoint Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/endpoints.md Register a route that responds to OPTIONS requests to get allowed HTTP methods. ```APIDOC ## OPTIONS /users/{id} ### Description Returns the allowed HTTP methods for a user resource. ### Method OPTIONS ### Endpoint /users/{id} ### Response #### Success Response (200) - `Allow` header (string) - Contains a comma-separated list of allowed HTTP methods. ### Response Example Allow: GET, POST, PUT, DELETE, OPTIONS ``` -------------------------------- ### Get user by ID Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/endpoints.md Retrieves a specific user by their unique ID. Returns the user object if found. ```APIDOC ## GET /api/users/{id} ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example { "id": "1", "name": "John Doe", "email": "john.doe@example.com" } ``` -------------------------------- ### Implementing PSR-15 Middleware Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/MiddlewareDispatcher.md Shows how to create a middleware class that implements the PSR-15 MiddlewareInterface. The process method handles the request and delegates to the next handler. ```php class MyMiddleware implements MiddlewareInterface { public function process( ServerRequestInterface $request, RequestHandlerInterface $handler ): ResponseInterface { // Process request $response = $handler->handle($request); // Process response return $response; } } $dispatcher->addMiddleware(new MyMiddleware()); ``` -------------------------------- ### Get Matched Route Instance Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RoutingMiddleware.md Retrieve the matched RouteInterface instance from the request attributes after routing has been performed. ```php $route = $request->getAttribute(RouteContext::ROUTE); ``` -------------------------------- ### Best Practices Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/RouteGroup.md Recommendations for organizing routes using groups and applying middleware effectively. ```APIDOC ## GET /api/users ### Description Retrieves a list of users. Input is validated. ### Method GET ### Endpoint /api/users ### Middleware ValidateUserInput::class ## POST /api/users ### Description Creates a new user. Input is validated. ### Method POST ### Endpoint /api/users ### Middleware ValidateUserInput::class ## GET /api/users/{id} ### Description Retrieves a specific user by ID. Input is validated. ### Method GET ### Endpoint /api/users/{id} ### Middleware ValidateUserInput::class ## GET /api/posts ### Description Retrieves a list of posts. Input is validated. ### Method GET ### Endpoint /api/posts ### Middleware ValidatePostInput::class ## POST /api/posts ### Description Creates a new post. Input is validated. ### Method POST ### Endpoint /api/posts ### Middleware ValidatePostInput::class ## All routes under /api ### Middleware AuthMiddleware::class -> CorsMiddleware::class ``` -------------------------------- ### ContentLengthMiddleware Constructor Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ContentLengthMiddleware.md Initializes the ContentLengthMiddleware. No parameters are required for its construction. ```APIDOC ## ContentLengthMiddleware Constructor ### Description Initializes the ContentLengthMiddleware. No parameters are required for its construction. ### Method ```php public function __construct() ``` ``` -------------------------------- ### Automatic Response Emission by Slim Application Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ResponseEmitter.md Shows how the Slim application's run() method automatically handles response emission. ```php use Slim\Factory\AppFactory; $app = AppFactory::create(); // ... register routes ... // Calls ResponseEmitter::emit() internally $app->run(); ``` -------------------------------- ### App Constructor Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/App.md Initializes the Slim Framework App with various dependencies for response creation, dependency injection, route handling, and middleware dispatching. ```APIDOC ## Constructor ```php public function __construct( ResponseFactoryInterface $responseFactory, ?ContainerInterface $container = null, ?CallableResolverInterface $callableResolver = null, ?RouteCollectorInterface $routeCollector = null, ?RouteResolverInterface $routeResolver = null, ?MiddlewareDispatcherInterface $middlewareDispatcher = null ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | responseFactory | `ResponseFactoryInterface` | Yes | — | PSR-17 response factory for creating HTTP responses | | container | `ContainerInterface | null` | No | null | PSR-11 service container for dependency injection | | callableResolver | `CallableResolverInterface | null` | No | null | Resolver for converting route handlers to callables | | routeCollector | `RouteCollectorInterface | null` | No | null | Collector managing route registration | | routeResolver | `RouteResolverInterface | null` | No | null | Resolver for matching requests to routes | | middlewareDispatcher | `MiddlewareDispatcherInterface | null` | No | null | Dispatcher for middleware stack execution | ### Request Example ```json { "example": "No request body for constructor" } ``` ### Response #### Success Response (200) None #### Response Example ```json { "example": "No response body for constructor" } ``` ``` -------------------------------- ### Function Name Callable Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/CallableResolver.md Use a string representing a function name as a callable. Examples include built-in PHP functions. ```php 'strlen' ``` ```php 'json_encode' ``` -------------------------------- ### Create Slim App from Container Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/AppFactory.md Instantiate a Slim application using definitions from a PSR-11 compatible container. This method automatically retrieves necessary factories and resolvers from the container. ```php use Slim\Factory\AppFactory; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; $container = new Container(); $container->set(ResponseFactoryInterface::class, $responseFactory); $app = AppFactory::createFromContainer($container); ``` -------------------------------- ### App Constructor Parameters Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/App.md The constructor accepts several dependencies, including a PSR-17 ResponseFactoryInterface, an optional PSR-11 ContainerInterface, and other core Slim interfaces for routing and middleware. ```php public function __construct( ResponseFactoryInterface $responseFactory, ?ContainerInterface $container = null, ?CallableResolverInterface $callableResolver = null, ?RouteCollectorInterface $routeCollector = null, ?RouteResolverInterface $routeResolver = null, ?MiddlewareDispatcherInterface $middlewareDispatcher = null ) ``` -------------------------------- ### Get Supported HTTP Methods Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/Route.md Retrieve an array of HTTP methods that the route supports. This is useful for understanding the route's capabilities. ```php $route = $app->get('/users', $handler); $methods = $route->getMethods(); // ['GET'] ``` -------------------------------- ### RoutingResults Class Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/types.md Represents the result of a route matching operation. It provides methods to get the route status, arguments, identifier, and allowed methods. ```APIDOC ## Class RoutingResults ### Description Result of route matching. ### Methods - `getRouteStatus(): int` - Returns the status of the route matching. - `getRouteArguments(): array` - Returns the arguments matched for the route. - `getRouteIdentifier(): ?string` - Returns the identifier of the matched route. - `getAllowedMethods(): array` - Returns an array of HTTP methods allowed for the route. ``` -------------------------------- ### Slim Framework File Organization Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/README.md Overview of the directory structure for the Slim Framework, highlighting key components and their locations. ```text Slim/ ├── App.php # Main app class ├── CallableResolver.php # Callable resolution ├── MiddlewareDispatcher.php # Middleware execution ├── ResponseEmitter.php # Response transmission ├── Factory/ # Factories │ ├── AppFactory.php │ └── ServerRequestCreatorFactory.php ├── Middleware/ # Built-in middleware │ ├── BodyParsingMiddleware.php │ ├── ErrorMiddleware.php │ ├── MethodOverrideMiddleware.php │ ├── OutputBufferingMiddleware.php │ ├── RoutingMiddleware.php │ └── ContentLengthMiddleware.php ├── Routing/ # Routing │ ├── Route.php │ ├── RouteCollector.php │ ├── RouteCollectorProxy.php │ ├── RouteContext.php │ ├── RouteGroup.php │ ├── RouteParser.php │ ├── RouteResolver.php │ └── RoutingResults.php ├── Handlers/ # Error handlers │ ├── ErrorHandler.php │ └── Strategies/ ├── Exception/ # HTTP exceptions │ ├── HttpException.php │ ├── HttpBadRequestException.php │ ├── HttpNotFoundException.php │ └── ... ├── Interfaces/ # Type definitions │ ├── RouteInterface.php │ ├── MiddlewareDispatcherInterface.php │ └── ... ├── Error/ # Error rendering │ ├── AbstractErrorRenderer.php │ └── Renderers/ └── Logger.php # Default logger ``` -------------------------------- ### Get Default Error Handler Source: https://github.com/slimphp/slim/blob/4.x/_autodocs/api-reference/ErrorMiddleware.md The getDefaultErrorHandler method returns the default error handler that is used for any exceptions not explicitly mapped to a custom handler. ```php public function getDefaultErrorHandler(): ErrorHandlerInterface|callable ``` -------------------------------- ### Run Built-in PHP Server Source: https://github.com/slimphp/slim/blob/4.x/README.md Command to run the built-in PHP development server for testing the Slim application. The public directory is set as the document root. ```bash php -S localhost:8000 -t public ```