Home > database >  What is the benefit using php attributes rather than static method
What is the benefit using php attributes rather than static method

Time:01-29

I use custom php attribute in my entity class,

and then there are service that read this attribute to prepare configuration array.

Something like this

class User implements UserInterface {

    #[GridUi(label: 'ID')]
    private int id;

    #[GridUi(label: 'Email address')]
    private string email;

    #[GridUi(label: 'Full name')]
    private string fullname;

}

But then I wonder, why not use static method like this

class User implements UserInterface {

    private int id;

    private string email;

    private string fullname;

    public static function getGridUiConfig()
    {
        return [
            'columns' => [
                ['label' => 'ID', field: 'id'],
                ['label' => 'Email address', field: 'email'],
                ['label' => 'Full name', field: 'fullname'],
            ]
        ];
    }
}

Now I use php attribute because this feels like best practice.

But in this case, what is the benefit using php attributes rather than static method?

CodePudding user response:

In your example? There is no benefit. By all means, use a static method.

Remember, attributes are for metadata that describes something about a side-effect or behavior associated with the class/method/property. Not internal functionality.

For instance: Let's say you have a Controller class (common for routers and MVC paradigms). Let's also say that you want a particular piece of functionality to occur before or after a given route method within that class (ie: middleware).

Rather than defining your middleware internally on the class, or forcing your router to worry about the internals of each class that it's responsible for, you can use attributes that augment the behavior of your request/response lifecycle based on the presence of these attributes.

Basically, it's syntactic sugar to allow you to simply mark certain things that other areas of the application can respond to.

CodePudding user response:

PHP 8 Attributes are a design pattern to add syntactic metadata.
Therefor there is no technical benefit, using them - afaik.

The actual benefits are, Attributes

  • can be namespaced
  • can have zero or more parameters to it
  • may resolve to class names
  • Attribute class names can be imported with use statements
  • There can be more than one Attribute to a declaration

Sticking to your example, it is obviously way more readable than the static function.

Its benefits exceed the difference shown in your example.
Personally, I'd say the best features are the reusability and readability.

  • Related