Why Control Flows Should NOT Be In XHP
About every six to nine months or so, an engineer at Facebook tries to add a control structure into XHP. These usually come in up to four flavors per diff:
$panel = userIsAdmin() ?
So much more efficient, right? Wrong! There’s a big difference between these two practices, can you think of it? Putting the conditional in XHP actually instantiates both outcomes. Because the conditions are only evaluated on render, they need to be instantiated even if they’re just going to be thrown away later. Plus, it may seem readable now, but what happens with nested statements?
<x:if cond={isLoggedIn()}> <x:if cond={isAdmin()}>
This is getting complicated quickly. XHP is really good at giving you an abstracted view at what the generated HTML structure will be, but this completely breaks that ability. I have to parse and separate out in my head the pieces that will be rendered. But really, you’re creating tons of objects just to throw them away, that should be enough to never do this.
Ok, so that eliminates
$list = <ul />;foreach ($items as $item) { $list->appendChild(<li>{$item}</li>);} $list = <ul> <x:foreach set={$items} fx={function($item) { return <li>{$item}</li>; }} /> </ul>;
Seems easy enough, and perhaps even beneficial to keep code in one place, but it’s important to notice that this is a fundamental shift in model. You’re creating wrapper objects to perform basic language operations. Remember that XHP is just syntactic sugar. Let’s look at what you’re really doing without the XHP syntax.
$ul = new ULElement( new Foreach($items, function($item) { return new LIElement($item); }));
That seems a little sillier now. It’s needlessly complicated and just serves to duplicate a standard language construct. Furthermore, that loop is only going to be evaluated and run on render, not when it’s instantiated. So if you have objects in there, they could be augmented by the time the loop is run and your output might not be what you expect. XHP is an extension to PHP to help with HTML rendering. It is not a language itself and should not be made to act like one. It can be very tempting — once you’ve invariably fallen in love with the XHP syntax — to want to make everything in XHP, but just remember that there is a time and a place for everything, and when it comes to control flows XHP is never the place.