Re: List of attributes

From: Date: Fri, 30 Oct 2020 19:28:41 +0000
Subject: Re: List of attributes
References: 1 2 3 4 5 6 7 8 9 10 11  Groups: php.internals 
Request: Send a blank email to internals+get-112150@lists.php.net to get a copy of this message
On 30/10/2020 18:47, Theodore Brown wrote:
While passing all nested attributes as an array would at least enable consistent semantics, it has the notable disadvantage of preventing some use cases from being expressed in PHP's type system. Specifically, how would you express that an attribute parameter must be passed a single attribute of a particular type?
I acknowledged this use case, but suspected, and still suspect, that it's rarer than the list-of-attributes case.
For example, suppose a developer wants to create/use an attribute like the following:
     #[Limit(
         min: 10,
         max: 100,
         error: #[CustomError(message: "...", notify: true, withTrace: false)]
     )]
What is the fundamental advantage of using an attribute as the argument here? The same thing can be expressed with an associative array:
    #[Limit(
        min: 10,
        max: 100,
        error: ["message" => "...", "notify" => true, "withTrace" => false]
    )]
The only thing that seems to lose is the ability to specify the allowed names and types of options - but those won't be checked by the ReflectionAttribute anyway, only once the actual constructor is run. So there's nothing really "attribute-y" about the CustomError class, and any "static object declaration" syntax would do, e.g.
    #[Limit(
        min: 10,
        max: 100,
        error: CustomError{message="...", notify=true, withTrace=false}
    )]
But if nested attributes are always passed as an array, the $error parameter would have to have an array type, which provides essentially no context about what is really required. The type system would be perfectly happy to allow an empty array, or an array with multiple values instead of the expected single CustomError attribute.
Again, this is a general problem, not one related to attributes: the Symfony validation examples would be best declared as requiring "Constraint[] $constraints" rather than "array $constraints".
3. Vote to switch to a less verbose syntax [...]
    The downside is that...
Let me stop you there. The downside is that a mob of Internals regulars will come to your house and lynch you for asking them to vote on the same thing yet again. It just ain't gonna happen. Regards, -- Rowan Tommins (né Collins) [IMSoP]

« previous php.internals (#112150) next »