Introducing Slim 4

cherif_b

Cherif Bouchelaghem

Posted on August 20, 2021

Introducing Slim 4

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.

$ mkdir slim-from-scratch && cd slim-from-scratch
Enter fullscreen mode Exit fullscreen mode
$ composer init
Enter fullscreen mode Exit fullscreen mode

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:

{
    "name": "cherif/slim-from-scratch",
    "autoload": {
        "psr-4": {
            "Cherif\\SlimFromScratch\\": "src/"
        }
    },
    "authors": [
        {
            "name": "Cherif BOUCHELAGHEM",
            "email": "cherif.bouchelaghem@gmail.com"
        }
    ],
    "require": {}
}
Enter fullscreen mode Exit fullscreen mode

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:

$ composer dumpautoload
Enter fullscreen mode Exit fullscreen mode

Install Slim 4

Installing Slim framework 4 is easy as running the following command:

$ composer require slim/slim
Enter fullscreen mode Exit fullscreen mode

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:

function (RequestInterface $request, ResponseInterface $response, array args) {
// Do whatever we want with the request and return a response
}
Enter fullscreen mode Exit fullscreen mode

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:

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();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()`.
Enter fullscreen mode Exit fullscreen mode

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:

$ composer require laminas/laminas-diactoros
Enter fullscreen mode Exit fullscreen mode

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.

That’s it.

💖 💪 🙅 🚩
cherif_b
Cherif Bouchelaghem

Posted on August 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related