Installation and first run
Slim is installed as an ordinary Composer package into an empty folder. It has no installer and no command that creates a project: you make the folder and the first file yourself.
What you need first
- PHP 8.1 or newer — check with
php -v; - Composer — check with
composer -V.
Installation
Create the project folder and install two packages:
mkdir blog
cd blog
composer require slim/slim:"4.*" slim/psr7slim/slim is the framework itself. slim/psr7 provides the request and response objects; Slim will not start without them. After the command the blog folder contains:
| File or folder | What it is |
|---|---|
composer.json | The list of project packages |
composer.lock | The exact installed versions |
vendor/ | Package code; never edited by hand |
The first file
Create the public folder by hand, and the file index.php inside it:
<?php
// public/index.php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write('Hello, Slim!');
return $response;
});
$app->run();What happens here:
requireloads the Composer autoloader — after that the package classes are available.AppFactory::create()creates the application object.$app->get('/', ...)declares a route: run this function for a request to/.- The function writes text into the response body and returns the response.
$app->run()handles the current request and sends the response to the browser.
Later examples leave out the <?php line, but in a real PHP file it always comes first.
Running
PHP has a built-in web server for development. Start it from the blog folder:
php -S localhost:8080 -t publicOpen http://localhost:8080 — the page shows "Hello, Slim!". The -t public option makes the public folder the site root. The server runs while the terminal window stays open; stop it with Ctrl+C.
A second page
Add one more route before the $app->run(); line:
// public/index.php
$app->get('/about', function (Request $request, Response $response) {
$response->getBody()->write('About the blog');
return $response;
});No restart is needed: open http://localhost:8080/about and you will see "About the blog".
Common mistake
A handler must return the response object. If you forget return $response, you get a type error instead of a page. Printing with echo is also wrong: the text bypasses the response object. Everything that should appear on the page is written with $response->getBody()->write().