Controllers

In Assegai, controllers are responsible for handling incoming requests and returning responses to the client. They are defined using classes and attributes, which allow Assegai to create a routing map that ties specific requests to the corresponding controllers.

Creating a controller

To create a controller in Assegai, you will need to use the #[Controller] attribute and a class. The #[Controller] attribute specifies that the class is a controller, and can also be used to specify a path prefix for all the routes defined in the class. For example:

src/Spears/SpearsController.php
#[Controller('spears')]
class SpearsController
{
...
}

This declares a controller class named SpearsController, with a path prefix of 'spears' for all the routes defined in this class.

Defining routes

To define a route in a controller, you will need to use an HTTP request method attribute (e.g. Get, Post, etc.) and a method. The request method attribute specifies the HTTP request method (GET, POST, etc.) that the route will be associated with, and the method defines the code that will be executed when a request is made to the route. For example:

#[Get]
function findAll(): string
{
  return 'This action returns all spears';
}

This declares a route in the SpearsController class that will be called in response to a GET request to the /spears route. The findAll() method is very simple, it just returns the string "This action returns all spears" as the response to the request.

TIP The method name is completely arbitrary and has no significance to Assegai. The only requirement is that you declare a method to bind the route to.

Manipulating responses

There are two ways to manipulate the response that is sent back to the client when a request is made to an endpoint:

1. Using the return value of the method:
In this case, the return value of the method is used as the response. This is what happens in the findAll() example above, where the string "This action returns all spears" is returned as the response to the request.
2. Using the response object:
Assegai also provides a response object that can be used to manipulate the response in more detail. For example, you can use the response object to set the HTTP status code, add headers, and write to the body of the response.

Controllers are an important part of the Assegai framework, as they allow you to handle incoming requests and return responses to the client. By using the #[Controller] attribute and HTTP request method attributes, you can easily define routes and bind them to specific methods in your controller class. Whether you choose to use the return value of the method or the response object to manipulate the response, Assegai provides you with all the tools you need to create powerful and flexible web applications.