Your First App
With Slim and a PSR-7 implementation installed, you're ready to write the smallest possible Slim
application: a public/index.php file that bootstraps the app, defines one route, and runs.
The Minimal index.php
Open public/index.php (create it if it doesn't already exist) and add this:
<?php
require __DIR__ . '/../vendor/autoload.php';
use Slim\Factory\AppFactory;
$app = AppFactory::create();
$app->get('/', function ($request, $response, $args) {
$response->getBody()->write("Hello, Slim!");
return $response;
});
$app->run();
Line-by-Line Walkthrough
| Line | What it does |
|---|---|
require __DIR__ . '/../vendor/autoload.php'; | Loads Composer's autoloader so every class from Slim and its dependencies becomes available without manual require statements. |
use Slim\Factory\AppFactory; | Imports the AppFactory class so it can be referenced simply as AppFactory instead of the full namespace. |
$app = AppFactory::create(); | Builds the Slim application object. Internally it picks a PSR-7 implementation (the one you installed, e.g. slim/psr7) automatically. |
$app->get('/', function (...) {...}); | Registers a route: when a GET request hits /, the closure runs. |
$response->getBody()->write(...); | Writes text into the outgoing response body. |
return $response; | Every route handler must return the response object — this is how Slim knows what to send back. |
$app->run(); | Starts Slim: it matches the incoming request against your routes and sends the response. This call must always be last in the file, after every route has been defined. |
Running It Locally
From your project's root folder (the one containing public/ and vendor/), start PHP's built-in server:
php -S localhost:8080 -t public
Now open http://localhost:8080 in a browser. You should see Hello, Slim!
printed on the page. If you instead see a blank page or an error, double-check that
vendor/autoload.php exists (meaning Composer install succeeded) and that you started the
server with -t public so it serves from the correct folder.