### Hello World Example
Source: https://www.slimframework.com/docs/v4/start/installation.html
A basic "Hello world!" application demonstrating Slim Framework setup and a simple GET route.
```php
get('/', function (Request $request, Response $response, $args) {
$response->getBody()->write("Hello world!");
return $response;
});
$app->run();
```
--------------------------------
### Create and Run a Slim 4 Application
Source: https://www.slimframework.com/docs/v4
This example demonstrates the basic structure of a Slim 4 application. It includes instantiation, middleware setup, route definition, and running the application. Ensure you have a PSR-7 implementation and a ServerRequest creator installed.
```php
addRoutingMiddleware();
/**
* Add Error 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
* @param LoggerInterface|null $logger -> Optional PSR-3 Logger
*
* Note: This middleware should be added last. It will not handle any exceptions/errors
* for middleware added after it.
*/
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
// Define app routes
$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name");
return $response;
});
// Run app
$app->run();
```
--------------------------------
### Instantiate and Run Slim Application
Source: https://www.slimframework.com/docs/v4/objects/application.html
This snippet shows the basic setup for a Slim application. It includes instantiating the app, adding error handling middleware, defining a simple GET route, and running the application. Ensure you have the Slim framework installed via Composer.
```php
addErrorMiddleware(true, false, false);
// Add route callbacks
$app->get('/', function (Request $request, Response $response, array $args) {
$response->getBody()->write('Hello World');
return $response;
});
// Run application
$app->run();
```
--------------------------------
### Install slim/php-view
Source: https://www.slimframework.com/docs/v4/features/php-view.html
Install the slim/php-view component using Composer.
```bash
composer require slim/php-view
```
--------------------------------
### Create Slim App with PSR-7 Response
Source: https://www.slimframework.com/docs/v4/concepts/value-objects.html
This example demonstrates setting up a basic Slim application. It defines a GET route that returns a JSON payload and sets the 'Content-Type' header. The application then runs to handle incoming requests.
```php
get('/foo', function (Request $request, Response $response, array $args) {
$payload = json_encode(['hello' => 'world'], JSON_PRETTY_PRINT);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
});
$app->run();
```
--------------------------------
### Install slim/twig-view
Source: https://www.slimframework.com/docs/v4/features/twig-view.html
Install the Twig-View component using Composer.
```bash
composer require slim/twig-view
```
--------------------------------
### Route Middleware Example
Source: https://www.slimframework.com/docs/v4/concepts/middleware.html
Example of adding a closure-based middleware to a specific route.
```php
handle($request);
$response->getBody()->write('World');
return $response;
};
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write('Hello ');
return $response;
})->add($middleware);
$app->run();
```
--------------------------------
### Install Slim PSR-7 Implementation
Source: https://www.slimframework.com/docs/v4/start/installation.html
Install the official Slim PSR-7 implementation for PSR-7 compliance.
```bash
composer require slim/psr7
```
--------------------------------
### Start PHP Built-in Server
Source: https://www.slimframework.com/docs/v4/start/web-servers.html
Use this command to start a local development server. Ensure you are in the public directory containing your index.php file.
```bash
cd public/
php -S localhost:8888
```
--------------------------------
### Install Slim Framework v4
Source: https://www.slimframework.com/docs/v4/start/installation.html
Use this Composer command to install the Slim Framework and its dependencies into your project.
```bash
composer require slim/slim:"4.*"
```
--------------------------------
### Install Laminas Diactoros
Source: https://www.slimframework.com/docs/v4/start/installation.html
Install Laminas Diactoros as a PSR-7 implementation.
```bash
composer require laminas/laminas-diactoros
```
--------------------------------
### Install Guzzle PSR-7 (v1) and Adapter
Source: https://www.slimframework.com/docs/v4/start/installation.html
Install Guzzle's PSR-7 implementation version 1 along with the http-interop adapter.
```bash
composer require guzzlehttp/psr7 "^1"
```
```bash
composer require sapphirecat/slim4-http-interop-adapter
```
--------------------------------
### Complete CORS Example Application
Source: https://www.slimframework.com/docs/v4/cookbook/enable-cors.html
A full example of a Slim Framework application demonstrating CORS implementation using middleware. It includes essential middleware for routing, error handling, and body parsing, along with custom CORS headers.
```php
addBodyParsingMiddleware();
// Add the RoutingMiddleware before the CORS middleware
// to ensure routing is performed later
$app->addRoutingMiddleware();
// Add the ErrorMiddleware before the CORS middleware
// to ensure error responses contain all CORS headers.
$app->addErrorMiddleware(true, true, true);
// This CORS middleware will append the response header
// Access-Control-Allow-Methods with all allowed methods
$app->add(function (ServerRequestInterface $request, RequestHandlerInterface $handler) use ($app): ResponseInterface {
if ($request->getMethod() === 'OPTIONS') {
$response = $app->getResponseFactory()->createResponse();
} else {
$response = $handler->handle($request);
}
$response = $response
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', '*')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->withHeader('Pragma', 'no-cache');
if (ob_get_contents()) {
ob_clean();
}
return $response;
});
// Define app routes
$app->get('/', function (ServerRequestInterface $request, ResponseInterface $response) {
$response->getBody()->write('Hello, World!');
return $response;
});
// ...
$app->run();
```
--------------------------------
### Install Nyholm PSR-7 and Server Components
Source: https://www.slimframework.com/docs/v4/start/installation.html
Install Nyholm's PSR-7 implementation and its server request creator for PSR-7 compliance.
```bash
composer require nyholm/psr7 nyholm/psr7-server
```
--------------------------------
### Redirect Route Example
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Defines a GET route that redirects requests from one URI to another with a specified HTTP status code. The `redirect()` method sets the `Location` header and the status code.
```php
$app->redirect('/books', '/library', 301);
```
--------------------------------
### Enable Apache Modules
Source: https://www.slimframework.com/docs/v4/start/web-servers.html
Install and enable the necessary Apache modules for URL rewriting. These commands require root privileges.
```bash
sudo a2enmod rewrite
sudo a2enmod actions
```
--------------------------------
### Install Doctrine Annotations
Source: https://www.slimframework.com/docs/v4/cookbook/database-doctrine.html
If you are using PHPdoc annotations for your entities instead of PHP8 attributes, install the doctrine/annotations package.
```bash
composer require doctrine/annotations
```
--------------------------------
### Create a GET Route
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Define a route that responds to HTTP GET requests. It accepts a route pattern and a callback function.
```php
$app->get('/books/{id}', function ($request, $response, array $args) {
// Show book identified by $args['id']
});
```
--------------------------------
### Install Guzzle PSR-7 (v2)
Source: https://www.slimframework.com/docs/v4/start/installation.html
Install Guzzle's PSR-7 implementation, specifying version 2.
```bash
composer require guzzlehttp/psr7 "^2"
```
--------------------------------
### Setting Slim Base Path for Sub-Directory Installation
Source: https://www.slimframework.com/docs/v4/start/web-servers.html
Configure the base path for a Slim Framework application when it's installed in a sub-directory of the server's root. This is done after creating the Slim app instance.
```php
setBasePath('/my-slim-app');
// ...
$app->run();
```
--------------------------------
### Slim 3 Container vs Slim 4 Container Setup
Source: https://www.slimframework.com/docs/v4/start/upgrade.html
Shows how to manage dependencies using a container in Slim 3 (Pimple) versus Slim 4, which requires a PSR-11 compatible container like PHP-DI.
```php
/**
* 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('');
};
```
```php
/**
* 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('');
});
```
--------------------------------
### Route Middleware Output
Source: https://www.slimframework.com/docs/v4/concepts/middleware.html
The expected HTTP response body when the route middleware example is executed.
```text
Hello World
```
--------------------------------
### Twig Template Example
Source: https://www.slimframework.com/docs/v4/features/twig-view.html
A basic Twig template file that displays a variable passed from the Slim application.
```twig
Welcome to Slim!
Hello {{ name }}
```
--------------------------------
### Getting Server Parameters
Source: https://www.slimframework.com/docs/v4/objects/request.html
Fetch environment-related data for the incoming request using the `getServerParams()` method.
```APIDOC
## Server Parameters
### Description
To fetch data related to the incoming request environment, you will need to use `getServerParams()`.
### Example
```php
$params = $request->getServerParams();
$authorization = $params['HTTP_AUTHORIZATION'] ?? null;
```
```
--------------------------------
### Advanced Error and Warning Handling in Slim
Source: https://www.slimframework.com/docs/v4/objects/application.html
This example demonstrates how to implement advanced error and warning handling in a Slim application. It involves setting up custom error handlers and a shutdown handler to catch notices and warnings, displaying an error page when they occur. The `$displayErrorDetails` variable controls whether detailed error information is shown.
```php
getCallableResolver();
$responseFactory = $app->getResponseFactory();
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();
$errorHandler = new HttpErrorHandler($callableResolver, $responseFactory);
$shutdownHandler = new ShutdownHandler($request, $errorHandler, $displayErrorDetails);
register_shutdown_function($shutdownHandler);
// Add Routing Middleware
$app->addRoutingMiddleware();
// Add Error Handling Middleware
$errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, false, false);
$errorMiddleware->setDefaultErrorHandler($errorHandler);
$app->run();
```
--------------------------------
### Install Doctrine ORM and DBAL
Source: https://www.slimframework.com/docs/v4/cookbook/database-doctrine.html
Add Doctrine ORM, DBAL, and Symfony Cache to your project using Composer. Symfony Cache is recommended for caching Doctrine metadata.
```bash
composer require doctrine/orm:^3.0 doctrine/dbal:^4.0 symfony/cache
```
--------------------------------
### Example PHP Template
Source: https://www.slimframework.com/docs/v4/features/php-view.html
A basic PHP template file that receives a 'name' variable and displays it. It includes proper HTML structure and uses htmlspecialchars for safe output.
```php
Slim Example
Hello, = htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>
```
--------------------------------
### Define a Doctrine Entity
Source: https://www.slimframework.com/docs/v4/cookbook/database-doctrine.html
Example of a Doctrine entity using PHP8 attributes. Convert to PHPDoc annotations if needed.
```php
'NOCASE'])]
private string $email;
#[Column(name: 'registered_at', type: 'datetimetz_immutable', nullable: false)]
private DateTimeImmutable $registeredAt;
public function __construct(string $email)
{
$this->email = $email;
$this->registeredAt = new DateTimeImmutable('now');
}
public function getId(): int
{
return $this->id;
}
public function getEmail(): string
{
return $this->email;
}
public function getRegisteredAt(): DateTimeImmutable
{
return $this->registeredAt;
}
}
```
--------------------------------
### Get All Headers
Source: https://www.slimframework.com/docs/v4/objects/request.html
Fetch all HTTP request headers as an associative array using getHeaders(). Keys are header names, and values are arrays of strings.
```php
$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
```
--------------------------------
### Add Custom Error Handler to Slim Application
Source: https://www.slimframework.com/docs/v4/middleware/error-handling.html
Map custom handlers for any Exception or Throwable. This example uses Monolog for logging and returns a JSON payload with the error message.
```php
addRoutingMiddleware();
// Optional: Define custom error logger
$logger = new Logger('error');
$logger->pushHandler(new RotatingFileHandler('error.log'));
// Define Custom Error Handler
$customErrorHandler = function (
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
) use ($app, $logger) {
if ($logger) {
$logger->error($exception->getMessage());
}
$payload = ['error' => $exception->getMessage()];
$response = $app->getResponseFactory()->createResponse();
$response->getBody()->write(
json_encode($payload, JSON_UNESCAPED_UNICODE)
);
return $response;
};
// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware(true, true, true, $logger);
$errorMiddleware->setDefaultErrorHandler($customErrorHandler);
// ...
$app->run();
```
--------------------------------
### Get Server Parameters
Source: https://www.slimframework.com/docs/v4/objects/request.html
Fetch data related to the incoming request environment using `getServerParams()`. This method returns an associative array of server and execution environment variables.
```php
$params = $request->getServerParams();
$authorization = $params['HTTP_AUTHORIZATION'] ?? null;
```
--------------------------------
### Create and Set Container
Source: https://www.slimframework.com/docs/v4/concepts/di.html
Instantiate a PSR-11 compatible container and set it on AppFactory before creating the Slim application.
```php
run();
```
--------------------------------
### GET Route
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Adds a route that handles only GET HTTP requests. It accepts the route pattern and a callback function.
```APIDOC
## GET /books/{id}
### Description
Handles GET requests for a specific book identified by its ID.
### Method
GET
### Endpoint
/books/{id}
### Parameters
#### Path Parameters
- **id** (string) - Required - The unique identifier of the book.
### Request Example
```php
$app->get('/books/{id}', function ($request, $response, array $args) {
// Show book identified by $args['id']
});
```
### Response
#### Success Response (200)
- The response for a successful GET request to retrieve book details.
#### Response Example
```json
{
"example": "response body"
}
```
```
--------------------------------
### Create Doctrine Console Application
Source: https://www.slimframework.com/docs/v4/cookbook/database-doctrine.html
Set up the Doctrine CLI application by retrieving the EntityManager from the container and passing it to ConsoleRunner. This script should be executable and can be placed at the project root or in a bin directory.
```php
#!/usr/bin/env php
get(EntityManager::class)));
```
--------------------------------
### Register Middleware with Slim Application
Source: https://www.slimframework.com/docs/v4/concepts/middleware.html
Demonstrates different ways to add middleware to the Slim application instance.
```php
// Add middleware to the App
$app->add(new ExampleMiddleware());
// Add middleware to the App using dependency injection
$app->add(ExampleMiddleware::class);
```
--------------------------------
### Get Service from Container in Route
Source: https://www.slimframework.com/docs/v4/concepts/di.html
Access services registered in the container from within a Slim application route using `$this->get('serviceName')`.
```php
/**
* Example GET route
*
* @param ServerRequestInterface $request PSR-7 request
* @param ResponseInterface $response PSR-7 response
* @param array $args Route parameters
*
* @return ResponseInterface
*/
$app->get('/foo', function (Request $request, Response $response, $args) {
$myService = $this->get('myService');
// ...do something with $myService...
return $response;
});
```
--------------------------------
### Middleware Execution Order (LIFO)
Source: https://www.slimframework.com/docs/v4/concepts/middleware.html
Illustrates the Last-In, First-Out (LIFO) execution order of middleware in Slim.
```php
$app->add(new MiddlewareOne());
$app->add(new MiddlewareTwo());
$app->add(new MiddlewareThree());
// Execution order: MiddlewareThree -> MiddlewareTwo -> MiddlewareOne
```
--------------------------------
### Create App from Container with Custom Dependencies
Source: https://www.slimframework.com/docs/v4/concepts/di.html
Use `AppFactory::createFromContainer()` to create a Slim application with dependencies already configured in the container. This is useful for setting custom factories like `ResponseFactoryInterface`.
```php
set(ResponseFactoryInterface::class, function (ContainerInterface $container) {
return new MyResponseFactory(...);
});
// Configure the application via container
$app = AppFactory::createFromContainer($container);
// ...
$app->run();
```
--------------------------------
### Getting the HTTP Request Method
Source: https://www.slimframework.com/docs/v4/objects/request.html
You can retrieve the HTTP request method (e.g., GET, POST, PUT) using the `getMethod()` method of the Request object.
```APIDOC
## Getting the HTTP Request Method
### Description
Inspect the HTTP request's method with the `Request` object method `getMethod()`.
### Example
```php
$method = $request->getMethod();
```
```
--------------------------------
### Get HTTP Request Method
Source: https://www.slimframework.com/docs/v4/objects/request.html
Inspect the HTTP request's method using the `getMethod()` method on the request object. Common methods include GET, POST, PUT, DELETE, etc.
```php
$method = $request->getMethod();
```
--------------------------------
### Define Routes for Slim-Instantiated Controller
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Define routes that point to methods within a controller class that Slim will instantiate. Slim passes the container to the controller's constructor if it accepts it.
```php
$app->get('/', "::class . ':home');
$app->get('/contact', "::class . ':contact');
```
--------------------------------
### Create an OPTIONS Route
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Define a route that responds to HTTP OPTIONS requests. It accepts a route pattern and a callback function.
```php
$app->options('/books/{id}', function ($request, $response, array $args) {
// Return response headers
});
```
--------------------------------
### Getting Content Type and Length
Source: https://www.slimframework.com/docs/v4/objects/request.html
Retrieve the request's 'Content-Type' and 'Content-Length' headers.
```APIDOC
### Content Type
You can fetch the HTTP request content type with the Request object’s `getHeaderLine()` method.
```php
$contentType = $request->getHeaderLine('Content-Type');
```
### Content Length
You can fetch the HTTP request content length with the Request object’s `getHeaderLine()` method.
```php
$length = $request->getHeaderLine('Content-Length');
```
```
--------------------------------
### HTML Form for File Uploads
Source: https://www.slimframework.com/docs/v4/cookbook/uploading-files.html
This HTML form demonstrates how to set up file uploads. Ensure the `enctype` attribute is set to `multipart/form-data`. Use brackets `[]` in input names for multiple files.
```html
```
--------------------------------
### Setting Base Path in Slim 4
Source: https://www.slimframework.com/docs/v4/start/upgrade.html
Demonstrates how to explicitly set the base path for your Slim 4 application when it's not deployed at the root of your domain.
```php
use Slim\Factory\AppFactory;
// ...
$app = AppFactory::create();
$app->setBasePath('/my-app-subpath');
// ...
$app->run();
```
--------------------------------
### Retrieving Query Parameters
Source: https://www.slimframework.com/docs/v4/objects/request.html
Get all query parameters from the request URI as an associative array using `getQueryParams()`.
```APIDOC
## Query String Parameters
The `getQueryParams()` method retrieves all query parameters from the URI of an HTTP request as an associative array.
If there are no query parameters, it returns an empty array.
**Usage**
```php
// URL: https://example.com/search?key1=value1&key2=value2
$queryParams = $request->getQueryParams();
```
```php
Array
(
[key1] => value1
[key2] => value2
)
```
To read a single value from the query parameters array, you can use the parameter’s name as the key.
```php
// Output: value1
$key1 = $queryParams['key1'] ?? null;
// Output: value2
$key2 = $queryParams['key2'] ?? null;
// Output: null
$key3 = $queryParams['key3'] ?? null;
```
**Note:** `?? null` ensures that if the query parameter does not exist, `null` is returned instead of causing a warning.
```
--------------------------------
### Slim 3 vs Slim 4 App Constructor
Source: https://www.slimframework.com/docs/v4/start/upgrade.html
Illustrates the difference in the Slim App constructor between v3 and v4. Slim 4's constructor is more flexible, accepting various factory interfaces.
```php
/**
* Slim 3 App::__construct($container = [])
* As seen here the settings used to be nested
*/
$app = new App([
'settings' => [...],
]);
```
```php
/**
* 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(...);
```
--------------------------------
### Getting POST Parameters
Source: https://www.slimframework.com/docs/v4/objects/request.html
Retrieve POST parameters from the request body when the method is POST and the Content-Type is `application/x-www-form-urlencoded` or `multipart/form-data`.
```APIDOC
## POST Parameters
### Description
If the request method is `POST` and the `Content-Type` is either `application/x-www-form-urlencoded` or `multipart/form-data`, you can retrieve all `POST` parameters.
### Example
```php
// Get all POST parameters
$params = (array)$request->getParsedBody();
// Get a single POST parameter
$foo = $params['foo'];
```
```
--------------------------------
### Slim Application for Handling File Uploads
Source: https://www.slimframework.com/docs/v4/cookbook/uploading-files.html
This PHP code demonstrates how to handle file uploads in a Slim Framework application. It retrieves uploaded files using `getUploadedFiles()` and moves them to a specified directory using the `moveTo()` method. It also shows how to handle single and multiple file uploads for different input names.
```php
build();
$container->set('upload_directory', __DIR__ . '/uploads');
AppFactory::setContainer($container);
$app = AppFactory::create();
$app->post('/', function (ServerRequestInterface $request, ResponseInterface $response) {
$directory = $this->get('upload_directory');
$uploadedFiles = $request->getUploadedFiles();
// handle single input with single file upload
$uploadedFile = $uploadedFiles['example1'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$response->getBody()->write('Uploaded: ' . $filename . '
');
}
// handle multiple inputs with the same key
foreach ($uploadedFiles['example2'] as $uploadedFile) {
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$response->getBody()->write('Uploaded: ' . $filename . '
');
}
}
// handle single input with multiple file uploads
foreach ($uploadedFiles['example3'] as $uploadedFile) {
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$response->getBody()->write('Uploaded: ' . $filename . '
');
}
}
return $response;
});
/**
* Moves the uploaded file to the upload directory and assigns it a unique name
* to avoid overwriting an existing uploaded file.
*
* @param string $directory The directory to which the file is moved
* @param UploadedFileInterface $uploadedFile The file uploaded file to move
*
* @return string The filename of moved file
*/
function moveUploadedFile(string $directory, UploadedFileInterface $uploadedFile)
{
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
// see http://php.net/manual/en/function.random-bytes.php
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
$app->run();
```
--------------------------------
### Get Content Length Header
Source: https://www.slimframework.com/docs/v4/objects/request.html
Retrieve the HTTP request's Content-Length header value using getHeaderLine('Content-Length').
```php
$length = $request->getHeaderLine('Content-Length');
```
--------------------------------
### Get Content Type Header
Source: https://www.slimframework.com/docs/v4/objects/request.html
Fetch the HTTP request's Content-Type header value using getHeaderLine('Content-Type').
```php
$contentType = $request->getHeaderLine('Content-Type');
```
--------------------------------
### Define Route with Controller and Middleware
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Define a route using a controller string and attach middleware to it. The middleware will execute before the controller action.
```php
$app->get('/course/{id}', Video::class . ':watch')
->add(PermissionMiddleware::class);
```
--------------------------------
### Get POST Parameters
Source: https://www.slimframework.com/docs/v4/objects/request.html
Retrieve all POST parameters when the request method is `POST` and the `Content-Type` is `application/x-www-form-urlencoded` or `multipart/form-data`. Use `getParsedBody()` for this.
```php
// Get all POST parameters
$params = (array)$request->getParsedBody();
// Get a single POST parameter
$foo = $params['foo'];
```
--------------------------------
### Add Closure Middleware to Slim App
Source: https://www.slimframework.com/docs/v4/concepts/middleware.html
Demonstrates adding both 'before' and 'after' middleware using closures. The 'before' middleware can short-circuit the request, while the 'after' middleware modifies the response.
```php
getHeaderLine('Authorization');
if (!$auth) {
// Short-circuit and return a response immediately
$response = $app->getResponseFactory()->createResponse();
$response->getBody()->write('Unauthorized');
return $response->withStatus(401);
}
// Proceed with the next middleware
return $handler->handle($request);
};
$afterMiddleware = function (Request $request, RequestHandler $handler) {
// Proceed with the next middleware
$response = $handler->handle($request);
// Modify the response after the application has processed the request
$response = $response->withHeader('X-Added-Header', 'some-value');
return $response;
};
$app->add($afterMiddleware);
$app->add($beforeMiddleware);
// ...
$app->run();
```
--------------------------------
### Get HTTP Response Body
Source: https://www.slimframework.com/docs/v4/objects/response.html
Retrieves the PSR-7 StreamInterface instance for the response body. This is preferable for large or unknown response lengths.
```php
$body = $response->getBody();
```
--------------------------------
### Get Uploaded Files
Source: https://www.slimframework.com/docs/v4/objects/request.html
Retrieve all uploaded files from the request. This method returns an associative array where keys correspond to the 'input' element names from the form.
```php
$files = $request->getUploadedFiles();
```
--------------------------------
### Register Middleware with Route or Route Group
Source: https://www.slimframework.com/docs/v4/concepts/middleware.html
Shows how to attach middleware to specific routes or route groups.
```php
// Add middleware to a route
$app->get('/', function () { ... })->add(new ExampleMiddleware());
// Add middleware to a route group
$app->group('/', function () { ... })->add(new ExampleMiddleware());
```
--------------------------------
### Get Single Header Value(s)
Source: https://www.slimframework.com/docs/v4/objects/request.html
Retrieve an array of values for a specific HTTP header using getHeader($name). A single header can have multiple values.
```php
$headerValueArray = $request->getHeader('Accept');
```
--------------------------------
### Getting Request Attributes in Route Callbacks
Source: https://www.slimframework.com/docs/v4/concepts/middleware.html
Retrieve variables set in middleware by calling the getAttribute() method on the request object with the corresponding attribute name.
```php
$foo = $request->getAttribute('foo');
```
--------------------------------
### Get Header Line as String
Source: https://www.slimframework.com/docs/v4/objects/response.html
Obtain a comma-separated string of all values for a given header using `getHeaderLine($name)`. This differs from `getHeader()` which returns an array.
```php
$headerValueString = $response->getHeaderLine('Vary');
```
--------------------------------
### Controller with Constructor Dependencies
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Define a controller class that accepts dependencies, such as a view renderer, in its constructor. This allows for dependency injection.
```php
view = $view;
}
public function home(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
// your code here
// use $this->view to render the HTML
// ...
return $response;
}
}
```
--------------------------------
### Get Specific Header Values
Source: https://www.slimframework.com/docs/v4/objects/response.html
Retrieve an array of values for a specific header name using `getHeader($name)`. Note that a single header can have multiple values.
```php
$headerValueArray = $response->getHeader('Vary');
```
--------------------------------
### Get All Response Headers
Source: https://www.slimframework.com/docs/v4/objects/response.html
Fetch all HTTP response headers as an associative array using the `getHeaders()` method. Each header name maps to an array of its string values.
```php
$headers = $response->getHeaders();
foreach ($headers as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
```
--------------------------------
### Enable Route Caching in Slim
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Enable router cache by setting a cache file path. The file needs to be writable during generation and only readable afterward. Consider generating in development and committing the cache file.
```php
getRouteCollector();
$routeCollector->setCacheFile('/path/to/cache.file');
```
--------------------------------
### Caddy HTTP Configuration
Source: https://www.slimframework.com/docs/v4/start/web-servers.html
Basic Caddy configuration for serving a Slim application over HTTP. It uses a PHP-FPM socket for FastCGI processing and sets the document root. Ensure php-fpm is running.
```caddy
:80 {
# Set-up the FCGI location
php_fastcgi unix//var/run/php/php-fpm.sock
# Set this path to your site's directory.
root * /var/www/public
}
```
--------------------------------
### Set Request Attribute
Source: https://www.slimframework.com/docs/v4/objects/request.html
Add a custom attribute to the request object. Attributes are useful for passing data between middleware and route handlers. This example adds session data.
```php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
$app->add(function (Request $request, RequestHandler $handler) {
// Add the session storage to your request as [READ-ONLY]
$request = $request->withAttribute('session', $_SESSION);
return $handler->handle($request);
});
```
--------------------------------
### Render PHP Template with Slim
Source: https://www.slimframework.com/docs/v4/features/php-view.html
Integrate PhpRenderer with a Slim application to render a PHP template. Ensure the template directory exists and the template file is correctly placed.
```php
get('/hello', function ($request, $response) {
$renderer = new PhpRenderer(__DIR__ . '/../templates');
$viewData = [
'name' => 'John',
];
return $renderer->render($response, 'hello.php', $viewData);
})->setName('profile');
$app->run();
```
--------------------------------
### Create an ANY Route
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Define a route that responds to any HTTP request method. It accepts a route pattern and a callback function. You can check the request method inside the callback using `$request->getMethod()`.
```php
$app->any('/books/[{id}]', function ($request, $response, array $args) {
// Apply changes to books or book identified by $args['id'] if specified.
// To check which method is used: $request->getMethod();
});
```
--------------------------------
### Get Single Header Value as String
Source: https://www.slimframework.com/docs/v4/objects/request.html
Fetch a single header's values as a comma-separated string using getHeaderLine($name). This differs from getHeader() which returns an array.
```php
$headerValueString = $request->getHeaderLine('Accept');
```
--------------------------------
### Implementing Method Overriding Middleware
Source: https://www.slimframework.com/docs/v4/start/upgrade.html
Shows how to add the `MethodOverridingMiddleware` to enable overriding HTTP methods via custom headers or request body parameters, similar to Slim 3's functionality.
```php
add($methodOverridingMiddleware);
// ...
$app->run();
```
--------------------------------
### Get All Query Parameters
Source: https://www.slimframework.com/docs/v4/objects/request.html
Retrieve all query parameters from the URI as an associative array using getQueryParams(). Returns an empty array if no parameters exist. Internally uses parse_str.
```php
// URL: https://example.com/search?key1=value1&key2=value2
$queryParams = $request->getQueryParams();
```
--------------------------------
### Controller Instantiated by Slim
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Define a controller that accepts the container instance in its constructor. Slim will automatically pass the container if the controller is not found in the container.
```php
container = $container;
}
public function home(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
// your code to access items in the container... $this->container->get('');
return $response;
}
public function contact(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
// your code to access items in the container... $this->container->get('');
return $response;
}
}
```
--------------------------------
### PSR-15 Middleware Implementation
Source: https://www.slimframework.com/docs/v4/concepts/middleware.html
Create PSR-15 compliant middleware by implementing the `MiddlewareInterface` and its `process` method for handling requests and responses.
```php
handle($request);
// Optional: Handle the outgoing response
// ...
return $response;
}
}
```
--------------------------------
### Get Response Status Code
Source: https://www.slimframework.com/docs/v4/objects/response.html
Retrieve the current HTTP status code of the response object using the `getStatusCode()` method. The default status code is 200 (OK).
```php
$status = $response->getStatusCode();
```
--------------------------------
### Create a PUT Route
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Define a route that responds to HTTP PUT requests. It accepts a route pattern and a callback function.
```php
$app->put('/books/{id}', function ($request, $response, array $args) {
// Update book identified by $args['id']
});
```
--------------------------------
### Configure and Add Twig-View Middleware
Source: https://www.slimframework.com/docs/v4/features/twig-view.html
Set up the Twig environment and add the Twig-View middleware to your Slim application. For production, configure a cache path for compiled templates.
```php
false]);
// Add Twig-View Middleware
$app->add(TwigMiddleware::create($app, $twig));
```
--------------------------------
### Route with Named Placeholder
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Defines a GET route that uses a named placeholder `{name}` in the URI pattern. The value of the placeholder is accessible in the `args` array within the route callback.
```php
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
// ...
$app->get('/hello/{name}', function (ServerRequestInterface $request, ResponseInterface $response, array $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name");
return $response;
});
```
--------------------------------
### Get HTTP Request Body Stream
Source: https://www.slimframework.com/docs/v4/objects/request.html
Access the raw HTTP request body as a PSR-7 StreamInterface. This is preferable for large or unknown-sized request bodies that may not fit into memory.
```php
$body = $request->getBody();
```
--------------------------------
### Route Callback with Dependency Injection
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Demonstrates using a Closure as a route callback when dependency injection is enabled. The `$this` keyword inside the Closure provides access to the DI container.
```php
$app->get('/hello/{name}', function ($request, $response, array $args) {
// Use app HTTP cookie service
$this->get('cookies')->set('name', [
'value' => $args['name'],
'expires' => '7 days'
]);
});
```
--------------------------------
### Get PSR-7 Request URI Object
Source: https://www.slimframework.com/docs/v4/objects/request.html
Fetch the PSR-7 Request object's URI object using the getUri() method. This object provides methods to inspect URL parts.
```php
$uri = $request->getUri();
```
--------------------------------
### Add Output Buffering Middleware
Source: https://www.slimframework.com/docs/v4/middleware/output-buffering.html
Configure and add the Output Buffering Middleware to your Slim application. The middleware supports APPEND (default) and PREPEND modes for handling response bodies.
```php
add($outputBufferingMiddleware);
// ...
$app->run();
```
--------------------------------
### Create a POST Route
Source: https://www.slimframework.com/docs/v4/objects/routing.html
Define a route that responds to HTTP POST requests. It accepts a route pattern and a callback function.
```php
$app->post('/books', function ($request, $response, array $args) {
// Create new book
});
```