Hey there,
PHP 8 introduced attributes – declarative meta-data which can get analyzed to control behaviour.
Most PHP-Developers already know similar technique called annotations like doctrine annotations.
I read some good articles to get a big picture of possibilities and techniques to use attributes.
https://stitcher.io/blog/attributes-in-php-8
https://www.amitmerchant.com/how-to-use-php-80-attributes/#practical-usage
https://platform.sh/blog/2020/php-8-0-feature-focus-attributes/
My first intention was to provide generics with attributes. But attributes are not made to add this complex feature.
Nevertheless I adapted a general way to resolve and process attributes to perform tasks like register Routes, attach Events, etc.
First of all I started with a spike to familiarize myself with the concepts and evaluate possibilities of attributes.
Separate PHP Package
I started writing a very small library which allows resolving attributes at class level (no functions atm) and automatically resolving when a class got auto-loaded.
The package (mbunge/php-attributes): https://github.com/mbunge/php-attributes
Upcoming features: https://github.com/mbunge/php-attributes/issues?q=is%3Aissue+is%3Aopen+label%3A%22upcoming+feature%22
I would also be appreciate for ideas, help, critical review or suggestions of your real-world examples of PHP 8 attributes!
very nice work, respect!
I use my DI container for this. It supports both polymorphism and attribute based autoconfiguration.
Already migrated what makes sense to attributes (Routes, Entities, RPC calls, Hydrator)
Currently working on trying to come up with a good method for handling middleware, though it might just end up in the route/rpc attribute instead of being its own dedicated one.
I’m loving attributes, but the my main annoyance is still needing phpdocs for psalm. I really really hope PHP introduces generics into the language spec (removed in parsing) to get rid of the need for phpdocs.
Where do I find your DI Container?
I published 2.1.0 of my lib, which add support for features I wrote above. This might help you with some of your problems 🙂
Generics may help a lot, but could also raise sources of errors. Nevertheless I love generics.
I’m having a bit of a hard time understating the purpose of this lib. Why is reflection being used? Am I missing something here? Is that how attributes must be interpreted in PHP8? Is there not a more strict runtime interpretation?
Didn’t bother to read past the first sentence?
Depends on field of use.
For example attach events, register routes, configure autowiring for a class, or anything else.
I opened an issue. I would appreciate suggestions for real-world examples.
I’m not sure why you’re being downvoted. His README makes it look like just another DI container.
I’m not quite sure what this package is actually supposed to do, it’s lacking examples and docs.