It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Workouts with Slim 3 - Part 3: Routing

By zooboole

Hi welcome to the third session of workouts with Slim 3 micro-framework. In the previous part I made mention of routes as important parts in any slim application. Today I will be taking you through how to use routes and what are their main characteristics. At the end of this part you should be able to set up a simple static website in just one hour.

Before I dive into the subject let me recall the definition of a route according to slim's official documentation.

A Slim app contains routes that respond to specific HTTP requests. Each route invokes a callback and returns an HTTP response.

From this we already know that our Slim application must have at least a route. Also note the fact that routes respond to specific HTTP requests, and we know that HTTP requests have what is called verbs or methods. When we look at the request example from the preview part of this series, you can notice that GET is the verb/method used:

GET / HTTP/1.1
Host: 0.0.0.0:8080

Each verb signifies the type of request we are makng to the server. For example, when you submit your contact forms you usually use the POST verb. That's mostly obvious because already in your HTML form you can add the method='POST' attribute.

Since Slim is specialized in handling HTTP requests and responses, it's very important to know which type of request your application makes everytime a request must be sent. URIs are the resources locators that will help us target specific information(web pages) in our servers so you also need to know each URI you are targeting with your requests. Once you provide this information to a route it will use a callback function(an anonymeous function) which will be in charge of returning the HTTP response to our client.

Creating route with Slim

The Slim framework makes it easy to create a route. When you want to create one, all you have to do is to use all information I mentioned above. The prototype of a route looks like:

Slim Route Explained

I have made this image to help you understand the main parts of id:

  1. The 1($SlimAppInstance) represents the instance of your slim app. The $app variable we created by making $app = new App().

  2. The number 2 (the HttpVerb) is a function located in the SlimApp() class. This function, likewise many other of the same type, are called proxies. They represent the real HTTP verb which caan be a GET, POST, DELETE, PUT, etc. By using this proxies you can easily tell Slim which method to use while sending the request. This verb(proxy) could then be $get(), $post(), $put(), ... depending on the type of request you want to make. Look at the full list here.

  3. The URI is the pattern which should match the resource your are requesting for. This can be a simple string or a regex pattern. It might be / for the root folder, /users/ to list users, /users/{id} to retrieve a user of a specific id, etc.

  4. The callbackFunction() is a closure. It's usually in the form of

    function($param1, $param2, $param3, ... $paramN){

    }

In my case it has only three parameters: $req, $res, and $UriParams. And here you may ask me what are those? Great! The $req variable actually contains the current HTTP request we are sending. The $res variable contains the HTTP response to be sent to our client(browser for example). The $UriParams is an array which contains any parameter passed to the URI in a form of `/users/{id}.

Note these variables names are not a standard. most of times you will see people using $request, $response, args. Remember the concept remains the same.

While we are on that why do we actually have to use these variables? The answer is that Slim supports PSR-7 interfaces for its Request and Response objects. If we want later on to access some methods of those interfaces like $withHeader() we will have to specify that we are using the PSR-7 interfaces. For that matter, from now on, on top of our Slim app we will always make use of these interfaces and garantee that our routes are using their current objects. So we will be adding following to our Slim app:

<?php

use \\Psr\\Http\\Message\\ServerRequestInterface as Request;
use \\Psr\\Http\\Message\\ResponseInterface as Response;
  1. The number 4 explains already the use of the parameters. The number 5 is actually an object of 'PsrHttpMessagesServerRequestInterface'.

  2. The number 6 is an object of 'PsrHttpMessagesResponseInterface'.

  3. This will contain all arguments passed to the route.

  4. The number 8 is the HTTP response the route returns. This response is and object of the 'PsrHttpMessagesResponseInterface'.

That's actually how a route is structured. To show an example, let me recall our fist route we created in the previous part of this tutorial:

$app->get('/', function($request, $response, $args){

    // Do anything here, like:
    echo "Welcome to Slim Town!";

    // Then return an HTTP response
    return $response;

});

That said let's add a route to our application for an about page. We want to access that page with the url http://0.0.0.0:8080/about. Our route will then look like:

$app->get('/about', function(Request $request, Response $response, $args){

    // Do anything here, like:
    echo "About Us <br>";
    echo" This is our about page ";

    // Then return an HTTP response
    return $response;

});

And we re-write our application as following:

<?php

    // Let's ask PHP to display all errors whenever they
    // occur in our slim code,
    // otherwise Slim will kind of swalow them, it will
    // only show in the command like.
    // Make sure you set this before other codes

    // The value mast become `false` before deployment
    ini_set('display_errors', true);

    // Call composer to autoload(make them available)
    // all classes from the the `vendor` folder

    // This file is in charge of doing that, and it's
    // located at vendor/autoload.php
    // Your folders structure might be different from mine,
    // make sure your adjust this relatively
    require __DIR__ . '/../vendor/autoload.php';

    // Let's announce to our application that we will be using
    // the Slim application class(`vendor/slim/slim/slim/App.php`) by calling its namespace. We don't need to require it with its
    // full path `vendor/slim/slim/slim/App.php`. Composer autoload
    // has already done that for us up there.
    use Slim\\App;

    // Use the PSR-7 HTTP Messages interfaces
    use \\Psr\\Http\\Message\\ServerRequestInterface as Request;
    use \\Psr\\Http\\Message\\ResponseInterface as Response;

    // We now get a new instance/Object of slim app itself
    // and we save it in a variable we can name `$app`
    // You can name this variable anything
    $app = new App();

    // We add our first route which will respond to the home page
    // request, usually located at `/` or root.
    $app->get('/', function(Request $request, Response $response, $args){

        // Do anything here, like:
        echo "Welcome to Slim Town!";

        return $response;
        // Then return an HTTP response
    });

    // We add a route for the about page
    $app->get('/about', function(Request $request, Response $response, $args){

        // Do anything here, like:
        echo "About Us <br>";
        echo" This is our about page ";

        // Then return an HTTP response
        return $response;

    });

    // Once we have the instance of SlimApp we can ask it to start running
    // the application by calling Slim's run() function
    $app->run();

Now we have two pages for our application. So far I have been using a closure as the callback of the routes, we can also use a class instead. Refere to Slim's official documentation to read more about different types of routes.

Conclusion

You have see how Slim offers you a very simple yet complex way of structuring your application routes. Up to now our routes have been able to spit out some standard text for us. What if we actually want to have a complex HTML page with plenty tags? Are we going to place it inside those routes? Definitely not. So in the next part I am going to talk of the Dependency Injection Container (DIC) and Slim Views. The DIC will allow us to connect(plug) many modules(like database, twig, monolog, etc) to our slim app. And Slim View will be the first module we'll bring in which will allow us to display more complex HTML pages.

Thanks for following. You know the tradition: if you like share with friends because sharing is caring.

Last updated 2024-01-11 UTC