Revision: Tue, 29 Oct 2024 10:57:42 GMT

Getting started — First HTTP controller

If you're using the Spiral for a PHP project and ready to dive into setting up your first controller, here are the basic steps 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.

To create your first controller effortlessly, use the scaffolding command:

php app.php create:controller CurrentDate

Note
Read more about scaffolding in the Basics — Scaffolding section.

After executing this command, the following output will confirm the successful creation:

Declaration of 'CurrentDateController' has been successfully written into 'app/src/Endpoint/Web/CurrentDateController.php'.

Now, let's inject some logic into our freshly created controller.

Here's an example of a 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 involves associating a route with your controller.

Create a route

Spiral simplifies route definition in your application by utilizing PHP attributes. You just need to add the #[Route] attribute to the controller's method, as shown below:

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 view the list of routes, use the following command:

php app.php route:list

You should observe your current-date route within the displayed list:

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

Test your controller

Once your controller is all set, it's time to test it out by running the RoadRunner server using 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: