Hacker News new | ask | show | jobs
by philo23 1133 days ago
Originally Symfony did use comments (docblock style ones like: /* @Route ... */) for this kind of thing, but since PHP 8 they've moved towards using attributes [1]. The syntax of the attributes #[Route(...)] might look like a comment, but they are actually just valid bits of code you can pragmatically inspect through reflection [2] and then choose to run if you want.

Docblock comments can also be inspected with reflection [3] but have a much looser syntax, so it was up to you to parse them. Where as you can create a new instance of an attribute directly from the reflection object [4]

In your example Symfony uses it to build up the list of HTTP routes by looking through all your controllers for #[Route] attributes. Generally that's done once and then cached, at least in production.

Personally I try to avoid using them, but they're definitely not comments. More like metadata you can attach to classes/methods/properties/parameters then use however you want.

[1]: https://www.php.net/manual/en/language.attributes.syntax.php

[2]: https://www.php.net/manual/en/reflectionclass.getattributes....

[3]: https://www.php.net/manual/en/reflectionclass.getdoccomment....

[4]: https://www.php.net/manual/en/reflectionattribute.newinstanc...

1 comments

> might look like a comment, but they are actually just valid bits of code

So comments that are code then.

Everyone can sit around going “This is not a pipe it’s a photo of a pipe or my perception of a photo of a pipe”. But if you did not have a sentence above your photo saying “This is not a pipe” or an arts teacher to tell you “this is not a pipe” and there was just a picture of a pipe on the page and someone pointed at it and said “can you tell me what that is?” You would say “why of course, it’s a pipe”. And then all of a sudden it started spouting water out of the end (let’s assume it was a GIF) then you can say “oh it looks like a pipe but it’s actually a water pistol masquerading as a pipe”. The fact that as a dev you have to constantly be on the look out for water pistols masquerading as pipes rather than having a clear distinction between pipes and water pistols is just a piss poor and easily avoidable design decision.

https://en.m.wikipedia.org/wiki/The_Treachery_of_Images