Routes and controllers

Basic functioning

When a client (e.g. a web browser) sends a request to a Vitya website, Vitya looks for the corresponding route. The route then calls the associated controller. The controller can either return a string that is sent back to the client as html, or send a response object.

We will present the response object more in details in the next chapters.

For now, let’s focus on the functioning of routes and controllers and where to find them.

Routes

You will find the routes.json file under private/app. After installing your minimal application, the file contains a sample route called homepage inside a pair of curly braces

{
    "homepage": {
        "path": "/",
        "callable": "App\\AppController::homepage",
        "methods": ["GET"]
    }
}

Here you can add your custom routes.

The value in the path line is what the client sends in order to call this particular route. The value in the callable line contains the location of the controller that corresponds to this route.

Controllers

By convention, all Vitya controllers are to be placed under private/app/src. This means that all the controllers of your application share the same namespace App.

The basic setup has already created an AppController.php file, our controller class:

namespace App;

use Vitya\Application\Controller\AbstractController;

class AppController extends AbstractController
{
    public function homepage(): string
    {
        $html = '<!DOCTYPE html>
            <html lang="en">
                <head>
                    <title>Homepage</title>
                </head>
                <body>
                    <h1>Hello world!</h1>
                    <p>This is a Vitya application.</p>
                </body>
            </html>
        ';
        return $html;
    }

}

In the example given, our class AppController extends the class Vitya\Application\Controller\AbstractController. Right after the namespace indication, the use line mentions the full name of the class, so that we can simply call it AbstractController from now on.

This example is the simplest kind of controller we can make: it takes no parameters, it returns an html string.

In the next chapters, we’ll see how we can pass parameters to a controller and how to call Vitya services inside our controllers.