Write PHP like JQuery

Posted: May 6, 2010

So I’ve certainly made my opinion of JQuery clear. As far as I’m concerned it’s really an integral part of the JavaScript language. The main thing it brings to the table is its drop-dead simple css-style selection and manipulation of the DOM.

However, another thing that many JQuery programmers really appreciate is the command chaining lets you pipe the object from one statement to another, futher shrinking the number of lines of code and in the process making it easy to just do a lot of different things in a row to one object.

$('.selectableClass').removeClass('selectableClass')
.addClass('unselectableClass').parent().children().slideUp();

That code is really concise, but it’s still pretty self-explanatory what’s going on. It doesn’t reach the level of unreasonable terseness of, say, the frackin’ ternary operator. (die ternary die!).

Wouldn’t it be great to make some of your PHP objects act like that? Guess what? You can!

There are a number of design patterns that can encourage working in your code this way. Decorators, for example. Obviously the factory pattern is all about creating and using brand new objects.

All you have to do is just pass the object you’re wanting to chain along back as the result of a method call. For example, you might have some kind of collection object that you add a new item to and then want to use that item immediately, as in the following example:

public function addItem($childItem) {
// add the child item
return $childItem
}

That’s all there is to it. You can then call the function like:

$collection->addItem(new childItem())->doSomethingOnChild();

In a more concrete example, say you’re creating a spreadsheet. You may want to create a new worksheet and new row all from a database.

$spreadsheet = new Spreadsheet()->addWorksheet(new Worksheet())->addRow(new Row())->manipulateRow();

Here, we’re piping in new objects as we create them and then using them right away.

Obviously this can get to be too much, so don’t go overboard with it. The above is getting a little bit long. But it can be a great practice to learn for certain design patterns and for hierarchial object relationships. And it shows that there’s more than one way to code your objects. It’s all about options.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Yahoo! Buzz
  • Propeller
  • Twitter

21 Responses to “Write PHP like JQuery”

Leave a Reply