Archive for May, 2008

PHP does NOT suck, and here’s why

I’m a huge fan of Jeff Atwood and his blog, Coding Horror. He writes in a very approachable manner, using a down-to-earth tone and easy-to-follow examples. He offers useful information to new and experienced coders alike. It’s the one blog I am sure to check on a daily basis. On more than one occasion, Jeff has made an insightful post about a topic that was paramount to a project I was working on. If you’ve never read his work, I can highly recommend the articles on SQL Joins, why upgrades aren’t always a good idea, passing the elevator test, and why the developer’s always at fault.

But the other day, a rare event occurred: Jeff made a claim with which I wholeheartedly disagreed. The post title, PHP Sucks, But It Doesn’t Matter, speaks for itself. Jeff lambastes the language on the whole, while freely admitting to its overwhelming success. The key quote:

I’ve written both VB and PHP code, and in my opinion the comparison is grossly unfair to Visual Basic. Does PHP suck? Of course it sucks. Did you read any of the links in Tim’s blog entry? It’s a galactic supernova of incomprehensibly colossal, mind-bendingly awful suck. If you sit down to program in PHP and have even an ounce of programming talent in your entire body, there’s no possible way to draw any other conclusion. It’s inescapable.

Well then I pulled off a movie-style escape, Jeff. I think the language is a success due to its design, and not in spite of itself. As a professional PHP developer, I think I’m also a bit more qualified than Jeff to comment on the strengths of the language.

Now, almost any discussion revolving around the pros and cons of a coding language can quickly devolve into angry flaming. Jeff of course avoids this pitfall, and I’m going to follow the same spirit of high discourse here. I’ve got two main concerns: there’s some severely flawed logic in the post, and Jeff completely disregards the many strengths of PHP, either deliberately or out of ignorance.

I responded to the logic issues in the comments of the post. Specifically, Jeff uses some fallacious arguments to back up his claim. You’ll have to read the post for yourself in order to grasp what I’m reacting to here (too long to quote). In all fairness to Jeff, I don’t believe he actually intended to make any underhanded arguments. Still, the content of the message is what it is, and ought to be addressed. Here’s the meat of what I said (modified and slightly edited):

By attempting to use facts to make a case for the languages goodness or badness, you commit a naturalistic fallacy. PHP doesn’t suck because it allows you to write function names in three different ways. It does not suck because you consider it ungraceful. It does not suck because crappy coders use it. By the same token, it does not rock because its used by some of the biggest web properties.

Secondly and to a lesser extent, you’ve got a “post hoc ergo propter hoc” (after this, therefore because of this). Just because you used what some consider to be crappy languages in the past, does not validate what you are saying now about PHP. While I can understand and appreciate the effort to “commiserate,” I feel it is expressed under false pretenses.

The claims of suckiness tend to revolve around PHP’s hodgepodge nature; the quotes actually speak to this facet of the language more than the post itself. Summarily, because the language works around other web technologies, it lacks the elegance and cleanliness of some other languages, such as Visual Basic (his example). The effects of a lack of elegance are not discussed, but I estimate that Jeff and the quoted authors would predict some ultimate detriment to the developer or user, most likely in the form of maintainability and the prevention of software rot.

I freely admit that PHP operates as a bit of a mashup, making reading difficult at times. But the problem isn’t with PHP itself, but rather the platform for which it was developed. By its nature, writing for the web is to blend a hodgepodge of technologies. A typical web page these days is equal parts HTML, CSS, and JavaScript, all tied together with PHP. The grassroots nature of the internet compels the development of a language that grows with and as these new technologies emerge and develop. The PHP foundation recognizes this and simply rides the tide.

That being said, I see a larger issue at work here: by valuing internal code elegance over direct markup access, languages like Visual Basic and Ruby on Rails treat browser web output like some kind of necessary evil. These languages tuck the HTML and JavaScript away in built-in libraries, classes and functions, so the developer needn’t ever get their hands dirty. You can write entire websites without even looking at actual web markup.

Am I the only one who feels that this approach does disservice to developers and their users?

My opinion is 180 degrees in the other direction. I really appreciate the fact that PHP works in concert with these technologies, as opposed to superseding them. It allows me to leverage what each technology does best, independently, to achieve my target action in the best way possible. Leaving it up to my server-side code to build the majority of a web page for me sacrifices way more control than I care to give up.

Jeff thinks PHP looks bad and is difficult to maintain. Fair enough. To that, I say web development is a lot like farming: a good website crop yield still requires a guy to get his hands in the HTML dirt a little bit. Always has, always will.

Personally, I think PHP looks pretty damn cool, jumping in and out of HTML. Mix in some dynamically generated JavaScript, or really juice it up by building AJAX from PHP, and you have the makings of some “shit hot” code. I have no trouble reading it, but then again I build on the platform professionally, full-time, and write in an excessively clean fashion. I’m sure Jeff can say the same for VB, as can practically any other professional coder in the language of choice.


Using jQuery for DOM event attributes

My last post discussed my conversion to JavaScript frameworks, and why you should be one too. I explained that I settled on jQuery because it simplified how I write JavaScript without strictly locking me into a set of features and effects.

A core part of this flexibility comes from jQuery’s document ready wrapper. It works like window.onload(), but provides a quantum leap in functionality. You can find more details at the link. Suffice it to say that all jQuery event listeners must go inside a document ready wrapper.

The problem is that document ready listeners only apply to DOM elements that exist when the document is ready. It works like a snapshot. When the document is finished loading, jQuery takes a picture of how it looks and references it for activating listeners.

“So what’s the problem?” you might ask. Anything that exists in DOM after that picture is taken essentially does not exist for listening purposes. Let’s look at an example. First, here’s a simple block of HTML:

[code='html']

generate new html

[/code]

…and the accompanying jQuery magic:
[code='js']
$(document).ready(function(){
$("a.currentAction").click(function(){
$("span#fooBar").append(
'

new action link'
);
});
$("a.newAction").click(function(){
alert('Here I am!');
});
});
[/code]

The link inside the span will create a new link using jQuery. That new dynamic link has its own jQuery listener to create a second new link as well. The catch is that the second link will never work; you’ll never see that alert box listed in line 8. The jQuery DOM doesn’t have an awareness of the second link at load time, so for its purposes the link doesn’t exist. Don’t believe me? Check out the demo I put together. I’ll wait.

Weird, right? Not to mention annoying…

So how can we daisy chain page dynamics using jQuery? Simple, we just have to go old school. Since jquery can’t listen to something that doesn’t exist at load time, we have to create a new listener. The easiest way to do that is using the onclick event. Let’s modify the JavaScript code from above a bit…

[code='js']
$(document).ready(function(){
$("a.currentAction").click(function(){
$("span#fooBar").append(
'

new action link'
);
});
});

function newClickAction(object) {
$(object).css({ backgroundColor:"yellow", fontWeight:"bolder" });
alert('Here I am!');
}
[/code]

This time, the new action stands on its own as a separate function, outside the document ready wrapper. We then added an onclick event to the generated HTML, thereby creating a new listener for the new link. The alert box will appear this time, and here’s another demo to show it in action.

There are two other things to note about this second example. First, notice that we have used jQuery code inside our custom function. The magic jQuery function $() is defined in the pages global scope. Since jQuery still must operate within the normal parameters of JavaScript, that function is available inside any other function. The thing to note here is that you can use jQuery outside of the document ready wrapper. This rule applies to any JavaScript library you might use.

The second thing to note in our second example is the argument called “object” passed into newClickAction(). This variable refers to the magic JavaScript variable this, which we placed inside our jQuery-generated HTML. The variable this always refers to the object in which it is called, whether it be a function or page element. jQuery is aware of the contents of a this reference, and thus can immediately identify the element by making it the sole argument of the $() function, as opposed to getting the element by id, class names, or tree navigation (i.e. parent descendant).

The two additional concepts are put into action when you click the link. jQuery finds the element and changes the background highlighting, while showing the alert box at the same time.

As you can see, things get pretty dicey quickly with uber-powered AJAX pages. Just make sure to keep your code clean, work on a single feature at a time, and you should be fine.


Congrats, Jennifer

For those of you who don’t know, “veterinarian” is Latin for “hellish education gauntlet.”

Anyway, today was my wife’s last day of veterinary school. I just got a phone call from Jennifer saying that she is on her way home, which means she’s done! Congratulations, sweetheart, I’m so very proud of you.


Get a JavaScript framework. Now.

We’ve been really into jQuery at our office for the past few weeks, and I have to say that I am absolutely in love with it. Coming from the world of writing “classical” JavaScript in “long-hand” format, jQuery appears damn close to magic; I half-expect a mystical gnome to pop out of my monitor when I use some of the more elaborate jQuery techniques. It’s that good.

If you still do JavaScript old-school, I would urge you by any means necessary to pick up and learn one of the several standardized JavaScript support libraries. It can only speed up your JS development, decrease your bugs, and perform some really cool JS acrobatics with relative ease. If you have any aspirations of utilizing Ajax techniques, frameworks are practically a requirement. The legwork involved in setting up an Ajax request manually is a real pain.

[aside]While a framework enables relatively easy Ajax effects, I recommend you build a simple Ajax effect totally on your own. I had a background in PHP/MySQL development before I even touched Ajax, and the experience was still challenging. Now when I use framework-powered Ajax, I know what’s going on behind the scenes, which makes me a better coder. Hmm, good future post fodder…[end aside]

Any of the big-name frameworks will get you started. When making your decision about where to start, I have one piece of advice: just pick one! Each has strengths and weaknesses, depending on your skill level and how you intend to implement it. The worst way to go about this would be to go around the web looking for insider advice on which one is the “best.” You’ll only find yourself in the middle of nit-picky flame wars. Such ridiculous arguments over different coding techniques/ tools are called “holy wars.” I find the term accurate.

At the same time, I don’t want you to wonder endlessly. Here’s what I would consider the top 4 (in no particular order):

Due to the nature of my work, most of my JavaScript is custom, and so I find the more “firm” frameworks restrictive. I personally lean towards jQuery because it focused on changing how you write core JavaScript, as opposed to providing me with prefab effects and formulas. But if your needs are simpler, the more formulaic frameworks, Script.aculo.us in particular, will suit you very well.

Before you start your next project involving JavaScript, learn to use a framework.  I promise you’ll wonder how the heck you got by with out it.