📌  相关文章
📜  slim 3 (1)

📅  最后修改于: 2023-12-03 15:20:09.720000             🧑  作者: Mango

Slim 3

Introduction

Slim 3 is a PHP micro-framework which is designed to help you quickly build simple yet powerful web applications and APIs. It's fast, low overhead, and provides a robust set of features for building everything from basic web pages to complex APIs.

Features

Below are some of the key features of Slim 3:

  • Lightweight and fast
  • Dependency Injection with Pimple
  • Routing
  • Middleware
  • HTTP Caching
  • Error Handling
  • Controller Classes
  • PSR-7 Support
Installation
Requirements
  • PHP >= 5.5.0
  • Composer
Installation via composer

You can install Slim 3 using Composer:

composer require slim/slim "^3.0"
Creating a Hello World application

Here's a simple example that demonstrates how to create a "Hello World" application using Slim 3:

<?php

require 'vendor/autoload.php';

$app = new \Slim\App;

$app->get('/hello/{name}', function ($request, $response, $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");

    return $response;
});

$app->run();
Routing

Slim 3 has a powerful routing system that makes it easy to map HTTP requests to PHP functions. Here's an example:

$app->get('/users/{id}', function ($request, $response, $args) {
    $id = $args['id'];
    // Fetch user from database
    $user = getUserFromDatabase($id);
    $response->getBody()->write(json_encode($user));
    return $response;
});
Middleware

Slim 3 has a Middleware system that allows you to modify the request and response objects before they are sent to the router. This is useful for things like authentication, logging, and error handling. Here's an example:

$app->add(function ($request, $response, $next) {
    // Authenticate user
    if (!isAuthorized($request)) {
        $response->getBody()->write(json_encode(['error' => 'Not authorized']));
        return $response->withStatus(401);
    }
    // Log request
    logRequest($request);
    // Pass control to next middleware
    $response = $next($request, $response);
    // Log response
    logResponse($response);
    return $response;
});
Conclusion

Slim 3 is a powerful PHP micro-framework that makes it easy to build simple yet powerful web applications and APIs. Its lightweight and fast and provides a powerful set of features for building everything from basic web pages to complex APIs.