Custom route attributes
PHP 8 introduces a new syntax called "attributes" (previously called "annotations" in earlier versions of PHP). These are used to provide metadata about a certain element (such as a class, function, or property) in the form of an attribute. Attributes are specified using the '#' symbol followed by square brackets. Here is an example of how to define an attribute:
#[AttributeName(key1: 'value1', key2: 'value2')] class MyClass { // code goes here}
To access an attribute, the ReflectionAttribute
class can be used. For example:
$target = new ReflectionClass(MyClass::class); $attribute = $target->getAttributes()[0]; echo $attribute->getName(); // prints the AttributeNameecho $attribute->getArguments()[0]; // prints value1echo $attribute->getArguments()[1]; // prints value2
Attributes can also be used to decorate functions and method parameters, as well as class properties.
Param attributes
Assegai provides a set of useful attribute decorators that you can use together with the HTTP route handlers. Below is a list of the provided attributes and the types they represent:
#[Req] |
Binds the current client `Request` to the target parameter. |
#[Res] |
Binds the current system `Response` object to the target parameter. |
#[Session] |
Binds the current session variables that are available to the currently executing script. |
#[Body(string $key, ?array $pipes)] |
Binds the current session variables that are available to the currently executing script. |
#[Query(string $key)] |
Binds the current client request `Query` object to the target parameter. |
#[Ip] |
Binds the current request IP address to the target parameter. |