Hacker News new | comments | show | ask | jobs | submit login
PHP Annotations Are a Horrible Idea (theunraveler.com)
104 points by theunraveler 1715 days ago | hide | past | web | 122 comments | favorite



This is pure horse pucky.

First of all PHP isn't about elegance and I find it a teeth grinding experience when people complain about it not being so. PHP is about getting stuff done.

He doesn't offer one good valid technical reason why not to use comments for meta-programming PHP other than "it just feels wrong" and an "icky feeling" which is entirely subjective. "Reliance on Yet Another Library"? C'mon.

The fact that you can even parse out comments with the reflection API lends, to me, that meta-programming is a-ok.

Also, his alternatives are kind of weak. Here's an annotation:

    /**
     * @Column(type="string", length=32, unique=true, nullable=false)
     */    
    protected $username;
And here's his proposed alternative:

    class User
    {
        public static $mapping = array(
            'username' => array(
                'type' => 'string',
                'length' => 32,
                'unique' => true,
                'nullable' => function() {
                    // Some logic to determine value.  
                }
            )
        );  
    }
I'll take the first one because I have other shit I need to do.


I disagree.

> First of all PHP isn't about elegance...PHP is about getting stuff done.

What language isn't about getting stuff done?

> He doesn't offer one good valid technical reason why not to use comments...

Not true. The OP explicitly points out that it breaks many PHP debugging capabilities.

> The fact that you can even parse out comments with the reflection API lends, to me, that meta-programming is a-ok.

So what? PHP also has a goto function. Should we use it just because we can?

> I'll take the first one because I have other shit I need to do.

Just because it's less verbose doesn't mean it's better. Otherwise, everyone would use Coffeescript instead of JS.


Many of the OPs complains have the tone of "not my PHP!!!".

If old PHP devs learn to look for annotations, points 2 and 4 no longer apply, and many points in 1 no longer apply either.

It sounds more like a PHP dev grumbling about change... (what else is new)


I am not opposed to change--in fact, I welcome it, especially with regard to PHP. Rather, I'm criticizing the use of annotations based on the argument that it is bad application design.


Making comments become as important as live code is never a good idea. This practice also encourages arbitrary syntax and would eventually lead to a mess of different standards with no cohesion.

Having a proper `pragma` declaration would be ideal.


> PHP also has a goto function. Should we use it just because we can?

Definitely yes. Use it whenever fit.


Here's a good, valid, technical reason: any meta-programming tool – even a well-designed one – that strips out comments will now change the meaning of your code and silently fail.

If the annotation were instead, say, not inside the comments, then any such tool would either (a) leave the annotation intact, or (b) fail with an error when it encounters the unknown syntax.


Please provide an example of such a tool for PHP. Also provide a working example of PHP code where removing all annotations causes working code to fail silently. In my experience with using annotations in PHP if the annotations are missing/invalid the compiling code throws very descriptive error messages.

Your good, valid, technical reasons are anything but.


Any editor that starts with comments collapsed is going to hide the functionality buried in comments. But that's a minor issue.

Comments are exactly that - comments. They are not intended to be executed and can be changed or removed at will. They are not necessary. They exist to provide further explication for code that is not self-documenting (or just plain programmer wankery).

This changes the deal. This means that some comments are required without providing clear boundaries to those who are not cognizant of the new convention.

PHP would be better served by adding naked @annotations and leaving comments to be non-parsed.


The examples in the annotations RFC that he links to actual use C# style attributes syntax:

  <Attribute(Value)>
  public class Sample { }
I think that's a better approach as it makes the annotations an actual language construct and keeps them out of comments.


I think this is quite a good technical reason:

    Because code comments should never be necessary for a script to function properly. 
In which other language do you see comment is necessary to make the code function properly?


In which other language do you see comment is necessary to make the code function properly?

Oracle SQL hints come to mind: http://www.dba-oracle.com/t_sql_hints_tuning.htm

There is it even worse because the hint may be needed to make your code run, but Oracle doesn't tell you whether or not the hint is actually in use or made a difference.


> In which other language do you see comment is necessary to make the code function properly?

If by "language" you mean "some library which also provides a separate but way more painful and verbose way of doing the same thing", then it existed in Java before Java 5 added annotations to the language itself.


I never know that, but still, the point stands: making a comment necessity for code to function properly is bad, bad, bad. That's why the Java folks throws it out right?


> I never know that, but still, the point stands: making a comment necessity for code to function properly is bad, bad, bad.

Not really.

> That's why the Java folks throws it out right?

I'm not sure what that's supposed to mean. "Java folks" don't throw anything out, Sun introduced a better and better-supported mechanism for doing what javadocs were coerced into doing.


> I'm not sure what that's supposed to mean. "Java folks" don't throw anything out, Sun introduced a better and better-supported mechanism for doing what javadocs were coerced into doing.

I mean the Java community didn't use it anymore, because the "annotation inside comment" thing is worse than "annotation supported natively by the language". Granted, it's the only practical way to do it in PHP for now, but it still didn't change the fact that it's bad, IMO.

I wonder why SensioLabs (the creator of Symfony and Doctrine) didn't make the PHP's annotation RFC into reality. They are a quite huge powerhouse in the PHP world...


> I mean the Java community didn't use it anymore, because the "annotation inside comment" thing is worse than "annotation supported natively by the language".

Sure, unless you don't have "annotations supported natively by the language".

> Granted, it's the only practical way to do it in PHP for now

Indeed.

> I wonder why SensioLabs (the creator of Symfony and Doctrine) didn't make the PHP's annotation RFC into reality. They are a quite huge powerhouse in the PHP world...

They might be a powerhouse, but they still aren't the drivers of PHP itself, Zend is. They can ask for the RFC to be finalized and implemented but at the end of the day, they also need to ship. And probably to ship on more versions than a hypothetical future 5.5.


[deleted]


> No, Java uses the same syntax with annotation inside comments.

Mostly incorrect, these are javadoc annotations which usually aren't used by code (aside from the javadoc extraction tool that is, and sometimes code editors for the @deprecated javadoc tag)

Since java 5, java has notations as language syntax e.g.

    /**
     * Some javadoc comment
     */
    @Annotation
    public void someMethod() {
        // stuff
    }
http://docs.oracle.com/javase/tutorial/java/javaOO/annotatio... which are supported by a formal extraction framework and are syntax- and type-checked by the java parser itself, and attached as metadata to classes and methods by the same.

Before java5, these were inside comments (alongside javadoc tags), fully processed by third-party tools and had no support from the JVM itself.


Its a syntax problem then ? what if the annotation wasn't inside comments would that make it ok ?


I think yes. It's ok if it's not inside comments. Just like any other language (I know at least C# and Java do this for example).


A lot of this boils down to PHP's feeble "array" declarator. Take a page from JavaScript and make it easy.


As of PHP 5.4 you can use [] to define arrays. It saves some typing, and is less noisy on the eyes I guess.


That's exactly the way it should be. Hopefully this will become the standard before long.


    He doesn't offer one good valid technical reason why not to use comments for meta-programming PHP other than "it just feels wrong" and an "icky feeling" which is entirely subjective.
Maybe it is subjective, but it sure gives me an icky feeling. You're breaking down a clear division between code and comment - fuzzing the lines. There's something about the idea that yes, I can only describe as being gross.

To each their own I guess, but it's not something I'd allow in one of my projects.


Some people don't like 4 space indentations, some don't like using tabs, and in most cases there's just an icky feeling behind it. Who's right?

In your own post, you give a reason for why you think (and not feel) it is wrong, and that's the right way to do. Icky feelings aren't. Maybe people saying that it feels wrong are crossing a line too?


You can be intuitively against something, but not be able to work out why. A few hours later, you often realize the rational reasons behind your original feeling.


Indeed, but what if you don't? I'm not saying that intuition is bad. I'm saying that intuition is bad when trying to make a reasonable point.


I'd agree with that, good insight.

Though I did make one (hopefully reasonable) point that it fuzzes the lines between code and explanation of that code, which I don't care for. The article also gives a valid reason that tools are not expecting this and won't correctly accommodate (though that could be considered a short-term problem).


Sure. I read it as "there is something wrong with it, but I can't pinpoint what", which is fair enough in my book. It's not like this is the lynchpin of the article.


It's noise in disguise to me: filler to make it look like he has more arguments than he really has.


If annotations are in comments, how are you going to leave actual comments containing annotations that you don't want to actually affect the code?


Easily, the annotation parser ignores all comments that it doesn't recognise.

    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * some comment that the doctrine parser will ignore completely
     */
    private $id;


by escaping them?

Some annotations are meant to affect the code, some aren't. Those who do and need to be given as pure comments need to be escaped.


So now you have a system for putting comments inside your comments? Are you going to eventually start putting meta-annotations inside your meta-comments, and inventing meta-meta-comments so you can comment on the meta-annotations?


Actually, no. What I have now is comment blocks which may contain normal annotations and escaped ones. There's no need to go deeper in meta-meta-something.

Regarding the comment inside comment system, if it were possible to have nested comments, it wouldn't be a problem anymore :). Since it's a Symfony convention, one could simply count the number of stars at the beginning of a comment line to know the meta-comment depth level. BTW, I know that you are being sarcastic here.

Anyway, this is beside the original problem. Annotations in comments are a problem, granted, but somewhat limited. It's easier and faster for a parser to look for comments and then annotations in them, rather than parse the whole PHP grammar augmented with annotations. Especially in PHP.


So now you have a system for putting quotation marks inside your strings? Are you going to eventually start putting escaped-quotation marks inside your escaped-quotes, and inventing escaped-escaped-quotation marks so you can quote the quoted-quotation marks?

In other words, there is no need for some kind of elaborate escapes-upon-escapes method here, all you have to do is not start a comment line with *@.


By not using / * * to start your comment block ?


If you're going to have different syntax for annotations and actual comments, why not choose a syntax that's properly different and not just a weird mutation?


Because they want something that is still valid PHP.


But why? Do I misunderstand that these annotations change the meaning of the code? Why would you want something that's still valid PHP without them, but means something else?


It's really bad practice. We all want to get stuff done, but don't complain when you end up in spagethi code hell. Some people are going to see that and think that's an ingenious use of comments, and then start to do the same in everything they write soon after. If you ever seen Preprocessor abuse in C++ you know what I mean.


give us a pointer to an example please.


That's a silly thing to require a citation for unless you're unfamiliar with preprocessor directives.


Some people may not be familiar with C macros, and an example could help grasp the problem you're talking about.

You could have pointed out all the things that are done in the C obfuscation code contests, to illustrate your point, but maybe this is silly. Also, you start your point from the spaghetti code hell that C macros let people fall into (I guess you where thinking about #ifdef conditionals), but I don't see how annotations could generate that problem. Imho, your point is flawed.

C macros are useful, and when not misleadingly used, very effective at abstracting things in order to get the important structures apparent. That is what annotations attempt to provide. Regarding PHP annotations, the problem here is that it's difficult and time consuming to parse a PHP script, whereas comments are an easy target. SensioLabs went the easy road, perhaps also in the hope that someday annotations would find their way in PHP, and people would just have to remove the comments around them to be compliant.


It's kind of funny cause his proposed alternative is how Doctrine originally worked...

http://docs.doctrine-project.org/projects/doctrine1/en/lates...


the official RFC for annotations is actually a little cleaner in syntax, easier to read and implemented in the language itself which is a way beter system than comment annotations. On a level I do agree that docblock comments are no place for annotations, it's the best we can have for now though, just until annotations become a native PHP feature.

Judging from the RCF and discussions on internals we still have a long way to go before we get annotations in PHP core.

http://marc.info/?r=1&w=2&q=b&l=php-internals... https://wiki.php.net/rfc/annotations


> the official RFC for annotations is actually a little cleaner in syntax, easier to read and implemented in the language itself which is a way beter system than comment annotations.

Sure, everybody knows that, but when the language does not have actual annotations yet (in whichever form they are), in-comment annotations are a very common choice. That's also what Java libs tended to use before annotations were added in Java 5.


Wow, I didn't know about those RFCs to make annotations a part of the language. Thanks for posting.


> ...because I have other shit I need to do.

Ironically, that's often also the attitude of programmers who don't use comments in their code (in any language).


To be fair, writing meaningful comments is really hard. So hard that the number of people who do it well is a small fraction of even the otherwise best programmers. To make matters worse, poor comments are worse than no comments at all. I can see why many programmers shy away from them.

* Comments that describe what the code does are a complete waste of time. The code already tells you what it does.

* Comments that describe why the code was written has more merit, but I cannot see how the following is any real improvement over the first point:

  // Investments of this type have always added the interest
  // to the principle. Who are we to question convention?
  $balance = $principle + $interest;
I am one of those poor commenters, so I really have no idea what could be said about that line that isn't already known. If you say not everything needs to be commented, then where does the line get drawn? In most cases, the vast majority of your code should be no less obvious than this.

* Some suggest the method signature and invariants should be documented, but that seems like just another exploitation of comments to deal with limitations of the language and is no better than putting annotations in the comments.

* I've seen code examples for using a given method in the comments, but that is better left to your test suite. Not only then can the reader see the example, but you can verify your method works at the same time without cluttering up the original codebase to boot.

If you are doing something weird, then yes, I am with you that comments are a big deal. However, if you are doing weird things on a regular basis I have to question your reasons for doing so. You shouldn't have to do weird things 99% of the time.

With that, teach us wise one. How can we all become great commenters so that we do not have to brush it off as something we do not have time for?


Comments regarding methods should be added to clarify how they are intended to be used, and what the results should be expected to be.

Comments within the code should be used to highlight things that are not what they seem. They should answer any "WTF?" questions that naturally arise. A typical example is something like "Hack: Need to pass fifth argument as -1 to avoid crash in broken library".

Comments that act like descriptive audio are useless.


I would love to see a good example of your first case. It is difficult to imagine and learn from it without seeing it action.

As I mentioned before, it seems the number of people who can actually pull off good comments are exceedingly small. I've looked at some prolific open source projects that have a decent amount commenting around method definitions as you suggest is good practice, but found the comments to be no more enlightening than just looking at the source code itself. I will assume they were just poor examples.

I do agree with everything else you said though.


I find it's best to describe what the argument are, as short names are rarely enough, and the return values or values supplied to callbacks under various conditions.

An example would be:

"Verify account takes an account ID, an optional enabled flag which, if specified, will only search for accounts that have a matching enabled status. The default is to search against all accounts. The return value is true if the account is valid, false otherwise."

These are extremely important in loosely typed languages where there is little indication as to what constitutes an acceptable argument. In a more rigid language like C++ there are usually a lot more hints in the language about what the input and output is.

Still, in programming "by contract" it is important to manage expectations and comments can communicate a lot of this.


Wouldn't that kind of information be better expressed in machine-human-readbale formats outside of the code that can be used to not only convey the information to the reader, but also verify that the description does as it says it does?

I will agree that some of that information is worth writing down, but I'm not yet convinced a comment within the code is the right place for it.

> These are extremely important in loosely typed languages where there is little indication as to what constitutes an acceptable argument.

Isn't that just pushing language "flaws" into the comments, not unlike annotations are being used here? I'll grant you that it is pragmatic when faced with lack of tools, but the grandparent suggested annotation comments were a bad idea but comments were a great idea, which seems contradictory to me in light of this.


The only "machine readable" comments I've seen that are useful are those structured in a simple, non-intrusive manner that makes generating documentation from them more automatic.

Remember that comments and documentation are no substitute for proper testing that will expose usage errors. No amount of machine readable specification can prevent this, so it's often a waste of programmer time to produce.


> Remember that comments and documentation are no substitute for proper testing that will expose usage errors.

Which is pretty much what I was getting at. Consider the following pseudo-code:

  Verify account takes an account ID, an optional enabled flag which, if
  specified, will only search for accounts that have a matching enabled
  status. The default is to search against all accounts. The return
  value is true if the account is valid, false otherwise.:

    account = new Account(id: 1)
    assert account.search does_not_include id != 1
It is human readable and machine parseable. You get your documentation, usage examples, and tests all in a place that is far better suited for the job, in my present opinion. I welcome being swayed though.

(I'm not sure that code even matches what your comment describes, but I couldn't really figure out what the comment was supposed to really intend the code to do, which brings me all the way back to my original points. Sorry.)


> I'll take the first one because I have other shit I need to do.

Uhh, what's so hard about making an array?


verbosity.


The reflection tools aren't meant for constant run-time use.

"PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions, methods and extensions. Additionally, the reflection API offers ways to retrieve doc comments for functions, classes and methods." [1]

It's an awesome way to generate automatic documentation for big projects. Of course it's possible to use it for other stuff like pointing to a template (though I'll point out that it can be done faster and more obviously by replacing it with a single function call at the end of the method), but "right tool for the job" and all that.

There's a very widely understood premise in programming that comments are blocks of text in source code files intended only to be read by humans and have no effect on program execution. When you change the semantics of something so well-defined... God help you.

Also worth noting in your sample code is that many ORMs simply query the DB for the schema and cache that result, so you don't need either of those. Merely being able to connect to your database is sufficient. The former comment (@Column) is a nice, short, human-readable format so developers can see what a column is, but having your code execution depend on that is crazy. What happens if someone minified [2] the code? Or ran it through a bytecode accelerator [3]?

I'm not going to stop anyone from abusing comments in their own codebase, but I sure as hell won't let this behavior infect mine.

[1]: http://www.php.net/manual/en/intro.reflection.php [2]: Yes, I know that's pointless in server-side source code - doesn't stop it from happening. [3]: http://www.php.net/manual/en/reflectionclass.getdoccomment.p...


Agree. Symfony and Doctrine 2 compile annotation to PHP anyway. I'ts much easier to use annotaions than xml or yamls configurations.


"PHP is about getting stuff done."

This implies that the road not taken by PHP (and thus the roads taken by other languages) are somehow unproductive. That's not accurate. Most languages are about getting stuff done. A tool can be explicit, or elegant, or whatever, and also help you get stuff done.

You are basically saying that PHP's design is at a global maximum for productivity and this is simply not true.


I think it was intended to mean that it eschews some advanced/clever functionality in favor of having a shallow learning curve. That doesn't make it the best tool for the job (nor does it prevent it from being so), but it implies that you can get started on solving your problem in thirty seconds rather than having to spend two hours prepping your dev environment and web stack any time you want to make a change.


Your second example is actually how Doctrine 1.2+ works. You could define your models in a YAML file which was then transformed into PHP classes at runtime.

That of course, leads to the issue of having your configuration separate from your implementation/code.


It would be pretty nice if PHP somehow slowly morphed into being about elegance, rather than becoming more and more horrible over time.


Part of getting things done is having maintainable code. This type of craziness is completely unnecessary.


Annotations are not required to use either of those libraries. Doctrine allows mapping information to be defined in XML or YAML files. For Symfony, the @Template annotation is not part of the core at all: it is part of the SensioFrameworkExtraBundle, which can be turned off easily. The normal way to render a template is:

    return $this->render("MyBundle:Controller:template.html.php", array(...));
That said, it would be easy enough to add the static variable-based mapping information to Doctrine as a metadata driver, and create a version of SensioFrameworkExtraBundle that does the same for its annotations.


> the PHP community is now officially so desperate for better metaprogramming capabilities that it is attempting to do so using code comments

This says it all ... and to be honest, from an ease point of view I like using annotations but as with most parts of PHP it's the implementation that sucks (or the lack of implementation)

Over 2 years ago a RFC has been filed for native php annotations and I must say that I like the idea of annotations being part of the actual language and not relying on Inflection on comments (wtf?) to attach metadata to classes, propeties or methods. Just too bad nobody can get their act together and get it implemented in the core. https://wiki.php.net/rfc/annotations


That somebody could be you!


Problem is not finding someone to implement it, problem is getting the core devs on one line concerning the syntax/implementations. There have been numerous suggestions but none were deemed good enough, and maybe for good enough reasons I might add.

http://marc.info/?l=php-internals&m=130496081925265&...


"Without the special @Template comment, Symfony does not know where to find the template file."

First off, this is completely false. With symfony2 the action needs to return a Response object. This annotation isn't required and the team I work with, we rarely use this.

It's very useful for when you are just adding a page that contains no real business logic.

"Doctrine 2 does the same thing when declaring object properties based on database table columns1:"

Oh look, there's a footnote.

"Fortunately, Doctrine also allows you to declare property metadata using PHP, YAML, or XML"

What?

"Because code comments should never be necessary for a script to function properly"

So your points are that we need @Template annotation to be able to render a template, which is FALSE, and you state the same with with Doctrine2 which you point out there are other ways to do it.

All your points for "DX Regressions" are completely wrong.

Unless I am using a special plugin with my IDE it's not going to link "AcmeBlogBundle:Post" to src/Acme/BlogBundle/Entity/Post.php. Most of what you point out is complete bullshit. What do I gain to hope by using var_dump() on an annotation? I know that in a Doctrine Entity that the column type is a string.

Articles and posts like this drive me banana's with the complete lack of understanding what you're writing about.


> First off, this is completely false. With symfony2 the action needs to return a Response object. This annotation isn't required and the team I work with, we rarely use this.

Correct. But if you want use the form where you just return an array of variables to use inside your template, and have Symfony smartly located the template for you, you have to use an annotation. See http://stackoverflow.com/questions/12922827/symfony-2-php-te... for an example.

> and you state the same with with Doctrine2 which you point out there are other ways to do it.

Yes, there are other BETTER ways to do it. Making comment-based annotations available as one of the ways pretty much guarantees that people will use it, and that seems like a bad idea to me. Just remove them so no one is able to choose the bad practice.

> All your points for "DX Regressions" are completely wrong.

Uhh, OK? How about comment folding in text editors? Would you, as a developer, be happy if you encountered some code that made heavy use of annotations for critical application logic? I wouldn't--this is what I mean by DX.

> What do I gain to hope by using var_dump() on an annotation?

The same thing you gain by var_dump()ing any variable--an understand of what's happening under the hood.


> Correct. But if you want use the form where you just return an array of variables to use inside your template, and have Symfony smartly located the template for you, you have to use an annotation. See http://stackoverflow.com/questions/12922827/symfony-2-php-te.... for an example.

Your point is that this is required, it's not. Using annotations is optional. The user you point to in the example wanted to use the annotations and wanted to use php templates.

The FACT is that in Symfony2, your Action MUST return a Response object. Using annotations is an easy way to get around this.

> Yes, there are other BETTER ways to do it. Making comment-based annotations available as one of the ways pretty much guarantees that people will use it, and that seems like a bad idea to me. Just remove them so no one is able to choose the bad practice.

Why is this a bad practice? Everything I need to now is right there in the annotation. I know that it's a string, integer, or anything else. I don't need to open up another file to check.

> Uhh, OK? How about comment folding in text editors? Would you, as a developer, be happy if you encountered some code that made heavy use of annotations for critical application logic? I wouldn't--this is what I mean by DX.

... You can't unfold them? You mean to tell me that having an editor that folds comments is bad design for the software that uses annotations? I'm trying to figure out this critical application logic you speak of. If I'm using annotations to describe a column that is a "string" type and has a length of "32" then what is the difference of it's in a yml or xml file? I enjoy being able to tell that as well as what relationships there are.

> The same thing you gain by var_dump()ing any variable--an understand of what's happening under the hood.

Again, why are you trying to var_dump something that has no value in using a var_dump on? An example of using var_dump and it being useful is "var_dump($user->getSomeRandomCrap())". It tells me what is returned by that method. Is an object or something else returned. WHY DO NEED to var_dump "@Column(type="string", length=32)"? I know the property should be a string and should be a max of 32 characters long?


Closures inside property initializations inside the class body don't work. Not even in an array.

So this code throws up a "Parse error: syntax error, unexpected 'function' (T_FUNCTION)"

    class User
    {
        public static $mapping = array(
            'username' => array(
                'type' => 'string',
                'length' => 32,
                'unique' => true,
                'nullable' => function() {
                    // Some logic to determine value.  
                }
            )
        );  
    }


Came here to post the same thing. I don't know if it has been fixed in 5.4, though.


Nope, the parser seems to be pretty brittle around this. Someone who knows more about the internals can probably explain why this works:

  class User
  {
      public $mapping = array(
          'username' => array(
              'type' => 'string',
              'length' => 32,
              'unique' => true,
          )
      );  

      public function __construct()
      {
      	$this->mapping['nullable'] = function() { echo "test"; };
      	$this->mapping['nullable']();
      }
  }

  $user = new User();
And this doesn't:

  class User
  {
      public static $mapping = array(
          'username' => array(
              'type' => 'string',
              'length' => 32,
              'unique' => true,
          )
      );  

      public static function set()
  	{
  		self::$mapping['nullable'] = function() { echo "test"; };
  		self::$mapping['nullable']();
  	}
  }

  User::set();


I used to be interested in helping fix PHP, but I gave up.

The reason is because Rasmus and a few others seem to think that using the syntax definition to do your type checking for you is a good idea, and that the hundreds of possible cases they didn't think of, don't matter.


Don't need to inline the function, it could instead just be a reference to static member of the same class: ... 'nullable' => self::getNullable, ...


'nullable' => self::getNullable

also won't work in any version of PHP


Couldn't agree more. Every time I use annotations I feel dirty...

Programmers who talk so much about code separation, clean modular structure etc are the same ones are willing to use annotations. What got into them?

Disclaimer: I like code to be elegant. And practical. This is PHP we're talking about, but no need to do more bad choices...


This could be solved if annotations were supported syntax. This works well in other languages (e.g. decorators in Python and annotations in Java)


And before annotations were added in java, the exact same hack was used for annotations. The alternative was to have separate configuration and mapping files which was painful. And then, you had libraries which did not have in-comment annotations and intermediate ones which compiled in-comment annotations to the original libraries's mapping files. Oh the fun we had.


(Python 3 has function argument and return annotations too)

I've made a static type checker for Python...

https://github.com/williame/obiwan


Agreed. A comment is an explanation about some part of the program. Not the program itself. Its meant to be ignored by the computer. Putting logic in the comments is just downright stupid. Its one of those overly "clever" things "smart" people do to make their code be cutting edge. Nope. As good as Symfony is, my main issue comes down to design decisions as this one. Its just dumb. Having logic in comments its like putting beer in baby formula, just in case I run out of beer. Shit doesnt make sense.


I've just ported java's bean vaidation to PHP using annotations in comments, and I strongly disagree.

Point by point:

1. dx regressions

I've designed the annotation system so that if developers misdeclare them an exception is thrown. Unit tests will fail, and the software will not run. Someone checking in code that fails to such a degree deserves what's coming to them. That covers php -l. Var_dump and debug_backtrace are irrelevant to my use case, and I use proper breakpoints and watches anyway (phpstorm + zend debugger). I don't even understand the point he's trying to make about IDE linking. Which leaves the argument about comment folding, which I think has some merit, if you think comments shouldn't be read, which I don't.

2. Readability

Nonsense. Learning an API always requires getting used to its idiosyncracies. His proposal to use static variables looks less readable to me.

3. Reliance on another library

Yes, that's kind of the point.

4. Icky feeling

Aha, bingo. The author came in with the opposite bias of myself and drew an according conclusion.

To conclude: the use of annotations in comments is not better or worse than alternatives, it's all in the eye of the beholder.


Somewhat related, I recently made a simple type annotation library and checker for Python 3...

https://github.com/williame/obiwan

Static type checking for Python yeah!


First of all, annotations are nothing new. They have been around in Java for years, and it was emulated because it had advantages that really don't need to be regurgitated by me. If they weren't a good idea, they wouldn't have lead to a formal adoption inside the language.

Secondly, in both Symfony2 and Doctrine2, annotations are an OPTION. You use them if you want to use them, and if you don't want to, you can use traditional configuration files. It doesn't seem that the author has done anything with either Symfony2 or Doctrine2, or he would have understood that. As someone who used Symfony1, ZF1, Propel and Doctrine, I would not go back to the old way of doing things, even if I was offered good money to do so (as happened just last week in fact).

Most people who actively use these components LOVE annotations, because they allow you to keep the configuration close to the code, and reduce verbosity.

They drive code generation, and reduce the amount of code that has to be written to get a specific job done. So if there's a problem debugging, is it really about annotations, or about code generation, and if we can't have code generation (facepalm) then I suppose we shouldn't have template systems like smarty or twig, simply because "debugging is harder" and editors have more work to do.

If it's not the author's cup of tea, nobody is forcing anyone to use these capabilities. Needless to say, I couldn't disagree with the premise of this article more. @jawngee already provided a simple salient example.


What's in the annotation is configuration, not application logic. As such there's no real difference between putting configuration into YML, XML and annotation comments.

In response to your 4 specific criticisms: 1. (DX regressions) - in theory yes, in practice the frameworks are good at this. The annotations compile down to PHP which you can look at directly, and you get exceptions if there is something wrong with the annotation. 2. (Decreased readability) - subjective POV. I find it easier, because the relevant configuration is next to the code to which it applies. It also prevents crufty out-of-date comments floating around. 3. (Yet another library) - Yep. No answer there. 4. (Icky feeling) - I get far more icky feelings out of seeing 30 lines of custom written 'setup code'. Annotations help to prevent that.


It violates the "I don't need to look inside comments for sources of bugs" rule I'm quite fond of.

I've defended PHP for some time now, but this is getting ridiculous.

Isn't PHP embedded inside markup? Wouldn't it be simpler to do something like:

?> < ... XML GOES HERE ... > <?php

and not violate any expectations?


> It violates the "I don't need to look inside comments for sources of bugs" rule I'm quite fond of.

I second that. A practical explanation of why this is dumb idea.

I get it, PHP is about getting stuff done. But why insisting on bad ideas, when PHP already has lots of them.


no that's bad really.

The best way to write PHP for the web is like any language: php echos or prints shit, that's it.

The way you're showing is that of the total noob trying to implement some php inside their evil dreamweaver website.

Besides, if you're handling markup (in the web context) on the server side, you've already failed, as most markup should only be generated client-side, diminishing server-load and bandwidth consumed while greatly improving cacheability.


I strongly disagree. Echoing well-formated HTML is much harder than simply tagging around it, and what's the benefit of echoing it? You like escaping characters?


You didn't read the whole post.

1) your js should be echoing the HTML and getting data through JSON ajax

2) echo and print both work in command line, are explicit and work exactly as any language, whereas peppering your shit with php tags looks like shit and a maintenance nightmare.

If you have trouble escaping characters, you should consider the single quote, it's known to rock the boat.

Additionally, "'.$var.'" is the best, fastest, cleanest no surprise approach to inserting variables in markup, leaving double quotes just fine and dandy inside your markup.

And then, I'm pretty sure I'd rather have a string with 100% warranty of no execution or interpretation (that's single quote versus double quote for me) than any kind of dirty markup polluting my source code.

On the same subject, there is no valid reason for having naked markup inside your PHP, or between PHP tags because you're just begging for problems.

And I would expect multiple PHP tags to cause some minimal parsing overhead too.

Either way this matters not because the only sane way to use PHP in a web application is echo json_encode($return); or header(file) + readfile

And even then the second example is only there because javascript can't be arsed to support file creation/download (i.e. server -> blob.gz -> js -> would you like to dload this shit ?)


I would argue that it's better for configuration and application logic should be separate though. You can run the same appliation with a different XML configuration without modification of the source. You couldn't do the same with in-comment configuration.


Wherever this is likely to happen, I wouldn't use annotations. For example, I use YML for environment specific variables.

But I don't need routes or fieldnames to be different only in one environment, so annotations work great there.


Fair enough. Then it sounds like your problem is really with annotations, and not that much about the in-comment part of this.


Yes, and it's not limited to PHP. I don't particularly like how Flask (python) uses decorators for its routing as well.


3) In this specific case we're reliant on Doctrine to read Doctrine annotations because we're already reliant on Doctrine to be Doctrine. Possibly relevant if the annotation reader was purely collecting metadata it did not use itself.


Not necessarily. Several Symfony components rely on doctrine/common simply for parsing annotations, even if you are not using Doctrine for anything else.


Oh okay. I'd never noticed that because I've always got doctrine in use anyway. /me wanders off to look more closely at the components.


Witch clearly proves that is a bad idea because it injects a dependency on some other lib


Seriously, what sort of argument is this... (Allow me to paraphrase) "PHP doesn't have annotations, so instead it has hacked up comments that stand in for annotations. I find these ugly because it's abusing comments/etc therefore the idea of having a non-ugly real implementation that removes most of my objections is a bad idea"

--EDIT I may have slightly not realised it was just comment annotations that were the problem here rather than annotations as a whole.... HOLD FIRE.


I added an update to the article. I wasn't aware of the RFC to make annotations a language feature when I wrote the article. The article is specifically referring to annotations implemented as code comments.

Sorry for the confusion, and thanks for your comment.


I fail to see how an array makes debugging say a routing directive easier. The issue is generally incorrect names or values which will not be aided by a backtrace or a var_dump - you know the value in either scenario. You will still have to dive into the parser and understand what it's looking for to resolve your problem or delve into XDebug.

In the situations when knowing the value of something does not help, I do not see why annotations wouldn't be superior.


At least you would know if your array contains a syntax error. With an annotation, you would have no way of knowing that aside from what the annotation parser spits out.


I found this very ironic.

I see PHP Annotations as a hack for comments. That said, I found very ironic someone giving a rant of a hack in hacker news. Just saying.. :)


There are hacks and then there are crutches.


I completely agree with you, but I would use something like this - http://pastebin.com/embed_iframe.php?i=U4Fmm0t6

I don't think that just an array quite make it as a real alternative but a definition builder called from a method seems more appropriate. Also I would seperate model definition from model repository.


Having used both doctrine and used a format of array mappings, I prefer the doctrine way of using annotations.

However I do also acknowledge that putting important information into comments can be somewhat dangerous. Doctrine does support storing metadata in yaml and xml files too, but in that case you need to ensure that changes to your model class get reflected in the mapping file.


Annotations (or decorators) are good idea as it is — they are very popular in Python. The bad part is that they are implemented horribly — as comment which are later parsed.

This should be implemented in PHP core or at least someone should write extension for it. That would solve implementation problems and add new, good feature to PHP language.


You don't need to use annotations with Symfony2. You can use yaml or xml configs if you want.

I have a big project written with Symfony2 - not a single annotation to be found.


DX - As in Developer Experience? That's a first for me.


Comments should be comments only, but your code in "alternative" is very dirty. Static(!) public(!) property is violation of encapsulation.


I don't understand how. It's a static property because it applies to all object of the class, not an individual object (i.e. an individual object shouldn't be able to change it).

And how is making the property public a bad idea? The configuration system that parses it will need to read the property, no? And a method like getUsername() should be reserved for actually getting the value of that field, not its config.


"It's a static property because it applies to all object of the class, not an individual object"

Why? if you will have 3 databases, each will have same password?

"And how is making the property public a bad idea?"

Because it's breaks encapsulation.

Also, there is two kind of "class" usages in PHP: as Object and as Structure. If your class is just Structure (contain no methods at all), then, of course, public properties is what we need. But when your class is an Object, which should have instances, API, then keep all properties encapsulated.


For me a lot of the fun in PHP in the last few years has been balls-to-the-walls metaprogramming.


PHP Is a Horrible Idea - FTFY


That article misses the point:

PHP OO is a HORRIBLE IDEA. if you're doing OO PHP, shoot your other foot right now and go learn PHP before using it java-style.

Why is it that every time somebody on HN explains that a technology is not suitable for a use case, it gets downvoted by fans of said technology ?


Why is PHP OO a horrible idea?


PHP OO is broken in many ways (of which you can find a list in the blog post "php a fractal of bad design"

PHP is naturally (due to it's C libs) non-OO and will thus only implement OO "that" far.

Lastly, OO is not a silver bullet and is best used only in front-end, and languages that were designed with it in mind.


Well, OOP in PHP seems to work rather well for thousands of large projects out in the wild - making your argument invalid.


Well, smoking cigarettes seems to work rather well for millions of successful people out in the wild - making your argument invalid.

It IS possible to make "business good" software in brainfuck, that's just not a reason to call it "not broken".

See, this is about science, logic, and whether or not a feature is properly supported by a language, not about whether or not somebody managed to build and sell a solution while using that feature.


  while (true)
     read("http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/");




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: