What is the purpose of the attributes? Attributes are intended to change the behavior of the method/class, or are they just extra data?
According to the documentation:
Attributes allow you to add structured and readable metadata information in code statements: classes, methods, functions, parameters, class properties and constants can be the destination of an attribute. Metadata defined by attributes can be inspected at runtime using the Reflection Apis [...]
Therefore, the attributes do not have the purpose of changing the behavior of the method or function, as in the case of Python Decorator, but only add metadata (extra information).
How do I recover the values of these attributes defined in the class or method?
As stated in the documentation, you need to use the Reflection API. The Reflection API allows you to access information from a class, function, method, parameters and etc.
Example:
#[Attribute]
class Route
{
public function __construct(protected string $path) {}
public function getPath()
{
return $this->path;
}
}
class UsuariosController
{
#[Route("/usuarios")]
public function index()
{
}
}
You could retrieve this information like this:
$reflection_method = new ReflectionMethod(UsuariosController::class, 'index');
foreach ($reflection_method->getAttributes(Route::class) as $reflection_attribute) {
$route = $reflection_attribute->newInstance();
echo $route->getPath(), "\n"; // "/usuarios"
}
Note that the class that represents your custom attribute always needs to contain the declaration #[Attribute]
in his statements.
Also note that the method Reflection::getAttributes
returns a array
of ReflectionAttribute
. This is because you can declare more than one attribute in a class or method.
Behold:
class UsuariosController
{
#[Route("/usuarios")]
#[Route("/usuarios/listar")]
#[RouteName("usuarios.listar")
public function index()
{
//
}
}
In this question, there is an answer that better explains the nature of the attributes:
https://answall.com/q/484081/5878, duplicated?
– Woss
@Woss agree that part of the question is duplicated, except for "how can I recover the defined values"?
– Wallace Maxters
In the other it is commented that it is via reflection. Perhaps you can ask the author of the reply to add an example there to make)
– Woss
Concomitant with being duplicate, asking for examples/clarifications in comment or even putting a reward would be better than creating a new question, at least in this case
– Costamilam
@Costamilam left open for community to decide. If you have an addition to the other answer, I think it’s worth closing that same.
– Wallace Maxters
I reopened the question. Details of how to implement the
Attribute
in the answers to the other question. The other answers only in part.– Wallace Maxters