Revision: Tue, 30 May 2023 16:57:50 GMT
v3.6 – outdated
This version of the documentation is outdated. Consider upgrading your project to Spiral Framework 3.7
Edit this page

Getting started — First HTTP controller

If you're using the Spiral for a PHP project and you're ready to set up your first controller, here are the basic steps you'll need to follow:

Create a controller

First things first, you'll need to create a controller. In Spiral, a controller is a class that defines the behavior of your application for a specific set of routes. It's responsible for handling incoming PSR-7 compatible requests, processing data, and then returning a response to the client.

Here's an example of a simple controller that returns the current date and time:

php
app/src/Endpoint/Web/CurrentDateController.php
namespace App\Endpoint\Web;

final class CurrentDateController 
{
    public function show(): string
    {
        return \date('Y-m-d H:i:s');
    }
}

The next step is to associate a route with your controller.

Create a route

Spiral makes it easy to define your application's routes by using PHP attributes. All you have to do is add the #[Route] attribute to the controller's method like so:

php
app/src/Endpoint/Web/CurrentDateController.php
use Spiral\Router\Annotation\Route;

// ...

#[Route(route: '/date', name: 'current-date', methods: 'GET')]
public function show(): string
{
    return \date('Y-m-d H:i:s');
}

To see the list of routes, use the php app.php route:list command in your terminal.

php app.php route:list

You should see your current-date route in the list:

+--------------+--------+----------+------------------------------------------------+--------+
| Name: | Verbs: | Pattern: | Target: | Group: |
+--------------+--------+----------+------------------------------------------------+--------+
| current-date | GET | /date | App\Endpoint\Web\CurrentDateController->show | web |
+--------------+--------+----------+------------------------------------------------+--------+

Test your controller

Once you have your controller set up, you'll need to test it by running the RoadRunner server with the command

./rr serve

Now you can test your controller by visiting the route in your browser. Just open the following URL in your browser: http://127.0.0.1/date



That's it! You've successfully set up your first controller in Spiral.


What's Next?

Now, dive deeper into the fundamentals by reading some articles: