Slim Framework

repository·4.x·Indexed 11 days ago

https://github.com/slimphp/Slim

A PHP micro-framework for building web applications and APIs. It requires PHP 7.4 or newer and a PSR-7 implementation to handle HTTP messages. The framework features a central Slim\App class for route definition and middleware management, including built-in routing, error, and body parsing middleware.

Tokens
1.7K
Snippets
8
Records
9
Agent score
46%

What's inside Slim

  1. Hello World with AppFactory

    4.x

    This example demonstrates how to bootstrap a Slim application using AppFactory. This method uses PSR-7 auto-detection to instantiate the application and handle requests without manual configuration, provided a PSR-7 implementation is installed via Composer.

    <?php
    use Psr\Http\Message\ResponseInterface as Response;
    use Psr\Http\Message\ServerRequestInterface as Request;
    use Slim\Factory\AppFactory;
    
    require __DIR__ . '/../vendor/autoload.php';
    
    // Instantiate App
    $app = AppFactory::create();
    
    // Add error middleware
    $app->addErrorMiddleware(true, true, true);
    
    // Add routes
    $app->get('/', function (Request $request, Response $response) {
        $response->getBody()->write('<a href="/hello/world">Try /hello/world</a>');
        return $response;
    });
    
    $app->get('/hello/{name}', function (Request $request, Response $response, $args) {
        $name = $args['name'];
        $response->getBody()->write("Hello, $name");
        return $response;
    });
    
    $app->run();
  2. Use Slim-Http Decorators

    4.x

    The slim/http library provides decorators for PSR-7 ServerRequest and Response objects. These are automatically detected and applied by Slim's internal factories if the package is installed.

    To disable automatic decoration, use AppFactory::setSlimHttpDecoratorsAutomaticDetection(false) and ServerRequestCreatorFactory::setSlimHttpDecoratorsAutomaticDetection(false).

    <?php
    
    use Slimactory\AppFactory;
    use Slim\factory\ServerRequestCreatorFactory;
    
    // Disable automatic decoration
    AppFactory::setSlimHttpDecoratorsAutomaticDetection(false);
    ServerRequestCreatorFactory::setSlimHttpDecoratorsAutomaticDetection(false);
    
    $app = AppFactory::create();
  3. Choose a PSR-7 Implementation

    4.x

    Slim requires a PSR-7 implementation to handle HTTP messages. You must install one of the following implementations to enable auto-detection with AppFactory::create():

    • Slim-Psr7: The official Slim implementation.
    • HttpSoft: Fast, strict, and lightweight.
    • Nyholm/psr7: High performance.
    • Guzzle/psr7: Includes extra functionality for stream and file handling.
    • Laminas Diactoros: The Laminas (Zend) implementation.
    # Install Slim-Psr7
    composer require slim/psr7
    
    # Install HttpSoft
    composer require httpsoft/http-message httpsoft/http-server-request
    
    # Install Nyholm/psr7
    composer require nyholm/psr7 nyholm/psr7-server
    
    # Install Guzzle/psr7
    composer require guzzlehttp/psr7
    
    # Install Laminas Diactoros
    composer require laminas/laminas-diactoros
  4. Add built-in Slim middleware

    4.x

    Slim provides several built-in middleware components that can be easily added to the App instance to enhance functionality:

    Routing Middleware

    Adds the built-in routing middleware to the stack. This is required for Slim to match incoming requests to defined routes.

    $app->addRoutingMiddleware();

    Error Middleware

    Adds the built-in error middleware to handle exceptions and errors. You can configure whether to display error details, log errors, and provide a PSR-3 LoggerInterface.

    $app->addErrorMiddleware(
        $displayErrorDetails, // bool
        $logErrors,           // bool
        $logErrorDetails,    // bool
        $logger              // LoggerInterface|null
    );

    Body Parsing Middleware

    Adds middleware to parse JSON, XML, or other form-encoded bodies into the request's parsed body property.

    $app->addBodyParsingMiddleware();
    $app->addRoutingMiddleware();
    $app->addErrorMiddleware(true, true, true);
    $app->addBodyParsingMiddleware();
  5. Run or handle a request in Slim

    4.x

    The App class provides two primary ways to process a request:

    run()

    This method is used to execute the application in a standard web server environment. It automatically creates a ServerRequest from PHP globals (if no request is provided), processes it through the middleware stack, and emits the resulting Response to the HTTP client.

    $app->run();

    handle()

    This method is used when you want to manually process a specific PSR-7 ServerRequestInterface. It traverses the middleware stack and returns the resulting ResponseInterface without emitting it. This is useful for testing or custom execution environments.

    $response = $app->handle($request);
    // Standard execution
    $app->run();
    
    // Manual handling
    $response = $app->handle($request);
  6. Add middleware to the App

    4.x

    You can add middleware to the application stack using the add() or addMiddleware() methods. add() is more flexible as it accepts a MiddlewareInterface, a string (class name), or a callable.

    Note that middleware is executed in a Last-In, First-Out (LIFO) order relative to how they are added.

    $app->add($middleware);
    // or
    $app->addMiddleware($middleware);
  7. The App class

    4.x
    The Slim\App class is the central entrypoint of a Slim application. It extends RouteCollectorProxy, meaning it provides a fluent interface for defining routes, and implements RequestHandlerInterface to handle incoming PSR-7 requests. It manages the middleware stack, the route resolver, and the execution lifecycle of the application.