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:
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:
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.
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:
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 |+--------------+--------+----------+------------------------------------------------+--------+
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.
Now, dive deeper into the fundamentals by reading some articles: