Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Slim 4 Cheatsheet

Getting Started

Install the framework with:

composer require slim/slim 4.*
composer require slim/psr7

We went with the slim/psr7 implementation of the request and response, but you can use others.

Then get started by putting the following in ./public/index.php

<?php
require_once(__DIR__ . '/../vendor/autoload.php');
$app = Slim\Factory\AppFactory::create();
$app->addErrorMiddleware($displayErrorDetails=true, $logErrors=true, $logErrorDetails=true);

$app->get('/', function (Psr\Http\Message\ServerRequestInterface $request, Psr\Http\Message\ResponseInterface $response) {
    $response->getBody()->write('Hello world');
    return $response;
});

$app->run();

run with:

php -S localhost ./public/index.php

Routing

Route Variables

Having a route like /hello?name=john is pretty ugly. It would be much nicer to have a route like /hello/john. You can use something like below to allow a variable name in the route and pass it to a function

$app->get('/hello/{name}', function (Psr\Http\Message\ServerRequestInterface $request, Psr\Http\Message\ResponseInterface $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});

References

Last updated: 15th August 2020
First published: 15th August 2020