I have just started working with symfony2 and have run across comment annotations.
Although comment annotation is not an inherent part of PHP, symfony2 adds support for this feature.
My understanding of commenting is that it should make the code more intelligible to the human. The computer shouldn't care what is in comments.
What benefits come from doing this type of annotation versus just putting a command in the normal PHP code?
ie-
/**
* @Route("/{id}")
* @Method("GET")
* @ParamConverter("post", class="SensioBlogBundle:Post")
* @Template("SensioBlogBundle:Annot:post.html.twig", vars={"post"})
* @Cache(smaxage="15")
*/
public function showAction(Post $post)
{
}
Best Answer
There are a few issues that immediately come to mind with comment annotations (and, particularly, symfony2's format):
/**/
comments are sent through to the compiled CSS, while non-CSS comments//
are eaten by the compiler; additionally, it makes it fairly easy to distinguish between the two, simply by looking at the first two characters).That said, doing something like this is not without its advantages.
Adding functionality that is not available natively in the language. First and foremost, this is probably the reason it's done this way by Symfony. PHP doesn't have decorators/annotations, and therefore, if you want that feature, you have to find a way to implement it. Even more, if you want it and don't want your users to be dependent on PHP extensions (because they can't always control that level of their environment), you have to find a way to do it internally that won't break the PHP compiler. Comments are the obvious choice.
Provide a clean way of adding various functionality to specific segments. Were I've seen annotations/decorators the most is Python, but you'll probably see it in a number of other languages, if you use them. For example, CherryPy uses it to expose functions as web page controllers (ie - a function with a specific decorator can be accessed by a browser, in the same way certain public functions in PHP controllers are accessed). They basically provide an "extension" capability to functions, or classes, offering utility features without cluttering the code inside the function.
Unfortunately, I don't know enough about Symfony to point out others with Symfony's format, but there's a lengthy discussion of the pros/cons of this in this Hacker News thread you might be interested in. You might also be interested in the request for change on the PHP site for native annotations.