Introducing Slim 4
Tags: php, slim, framework, routing
Published: 2021-08-20 20:45:52

Slim framework is a PHP micro framework that could be used to write web applications and web services APIs, unlike other known frameworks like, Symfony, CakePHP or Laravel, Slim doesn’t have any opinion on what templating engine or what ORM should be used, all it provides is a routing system that takes a web request and returns a response depending on the application logic behind the route.

## Application initialization using Composer
The article assumes that composer is already installed and the reader knows how to use it in the command line.

```shell
$ mkdir slim-from-scratch && cd slim-from-scratch
```

```shell
$ composer init
```

Is it possible to leave the default answers for the composer questions in the command line.
A composer.json file should be created with the entered value from the command line.

## Configure classes autoloading in composer.json
Depending on the composer installed version, a `src` folder can be created and the autoloading is configured, form me is:
```json
{
    "name": "cherif/slim-from-scratch",
    "autoload": {
        "psr-4": {
            "Cherif\\SlimFromScratch\\": "src/"
        }
    },
    "authors": [
        {
            "name": "Cherif BOUCHELAGHEM",
            "email": "cherif.bouchelaghem@gmail.com"
        }
    ],
    "require": {}
}
```

The autoloading should be added as above, if the autoloading was not generated automatically, just change `Cherif` which is my vendor name by your vendor name.

Once the autoload key in composer is configured the following command must be run in order to expose our code to compose autoloader:

```shell
$ composer dumpautoload
```

## Install Slim 4
Installing Slim framework 4 is easy as running the following command:
```shell
$ composer require slim/slim
```

## The first request handler
In its heart Slim 4 is a `PSR-15` middleware dispatcher, it takes a `PSR-7` request message and returns a `PSR-7` response message using a request handler.
The request handler is just a callback function for a given route that could be in the following signature:

```php
function (RequestInterface $request, ResponseInterface $response, array args) {
// Do whatever we want with the request and return a response
}
```

Note, `RequestInterface` and `ResponseInterface` are provided by the PSR package.

To see this in action, create a `public` folder in the project root and add an `index.php` file that will act as the main file for the Slim application.
For now the `index.php` can have the following code:

```php
require dirname(__DIR__) . '/vendor/autoload.php';

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Slim\Factory\AppFactory;

$app = AppFactory::create();

$app->get('/', function (RequestInterface $request, ResponseInterface $response, array $args) {
    $response->getBody()->write('Hello from Slim 4 request handler');
	return $response;
});

$app->run();
```

The code above is short and self explanatory:

The `use …` is for the dependencies.
`$app = AppFactory::create();` is where the Slim application is instantiated
`app->get ...` is to configure the routes, here we have just a one GET route.
`$app->run` runs the application and returns a response.

To run the application use your local web server of choice.
I like to use the PHP built in static server like the following:
```
$ php -S localhost:8000 -t public
```
The command line is executed from the root folder of the application to point the server to the public directory.
When visiting `http://localhost:8000/` in the browser an exception should be throwing in the console saying:
```
 Uncaught RuntimeException: Could not detect any PSR-17 ResponseFactory implementations. Please install a supported implementation in order to use `AppFactory::create()`.
```
The exception says that Slim could not be run without providing a `PSR-17` implementation, let’s install one.

## Install `laminas/laminas-diactoros` for PSR-7 and PSR-17 implementations

`PSR-7` and `PSR-17` are PHP HTTP messages standards proposed by the community; we can find several implementations for them out there.
`laminas/laminas-diactoros` is one of the implementations that I usually use, it can be installed using composer as the following:

```shell 
$ composer require laminas/laminas-diactoros
```

Now, when the browser page is refreshed, the application response `Hello from Slim 4 request handler` should be printed.

The source code of this article can be found in [GitHub](https://github.com/cherifGsoul/slim-from-scratch).

That’s it.