Method Chaining in MooTools and PHP

By  on  

One of the great parts of most every JavaScript and PHP framework these days is the ability to chain class methods. I've gotten quite a few question about how this is possible so I want to cover the basics of allowing chaining in your own custom classes.

Lets first start by implementing some new methods on the MooTools Element class:

/* implement functionality */
Element.implement({
	doTaskA: function() {
		/* do stuff */
	},
	doTaskB: function() {
		/* do stuff */
	}
});

What the above methods actually do really isn't very important per this post. Now that you have these methods in place, you try the following:

/* Example */
$('myElement').doTaskA().doTaskB();

Good? Nope. You'll end up with the following error:

$('myElement').doTaskA() is undefined

What? doTaskA() definitely exists!! Why is this error occuring? While doTaskA() does exist, the method doesn't return anything.

The strategy for method chaining is returning a reference to the current object. How? Lets update the doTaskA() and doTaskB() methods to allow for method chaining:

Element.implement({
	doTaskA: function() {
		/* do stuff */
		return this;
	},
	doTaskB: function() {
		/* do stuff */
		return this;
	}
});

Returning this keeps the reference which in turn keeps the ability to chain alive. You can do the same thing in PHP:

public function doTaskA() {
	return $this;
}

public function doTaskB() {
	return $this;
}

/* usage */
$myObject->doTaskA()->doTaskB();

Class method chaining is a great way to keep your code condensed. Don't get too carried away with chaining though -- be sure to balance chaining with readability.

Recent Features

  • By
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

Incredible Demos

  • By
    Drag & Drop Elements to the Trash with MooTools 1.2

    Everyone loves dragging garbage files from their desktop into their trash can. There's a certain amount of irony in doing something on your computer that you also do in real life. It's also a quick way to get rid of things. That's...

  • By
    MooTools TwitterGitter Plugin

    Everyone loves Twitter. Everyone loves MooTools. That's why everyone should love TwitterGitter, a MooTools plugin that retrieves a user's recent tweets and allows the user to format them however the user would like. TwitterGitter allows the user to choose the number of...

Discussion

  1. I had no idea you could chain methods like that in PHP. I was trying to think of a way to do exactly that just last night, and couldn’t figure it out. Champion!

  2. I’m affraid that it’s not possible to do method chaining natively in PHP. I’m used to use this synthax in most PHP frameworks and I didn’t knows that wasn’t a native feature ! I have learn something :)

  3. i’ve been searching this tips for a long time now :) i think i’ll have to recode some of my classes :)

    thanx for the tips (again)

  4. It’s one of the best tips I’ve ever read! Thanks!

  5. jem

    Took me a while to get in the habit of always returning some object in functions or class methods.

    Also don’t forget about the chain method that a lot of native mootools classes support, i use it a fair bit when working with FX.

    var myTween = new Fx.Tween($('someElement'), {property: 'opacity'}).set(0).start(1).chain(function() { /* do something when tween completes */})
  6. Cool stuff. I recently wrote two php classes Rules and Access. The rules class has basic validation methods like isSunday() isAdmin() etc. each do a boolean check setting a class param and returns $this. The the Access class is really just a namespace for static methods like isAdminAndSunday() that simply returns the result from RulesInstance->isSunday()->isAdmin()->get();

    Very decent stuff once you figure out usage for it

  7. Thtas a clever little tip there, thanks!

  8. Chris the Developer

    AFAIK, method chaining is only available in PHP 5.

  9. Very nice articles. all are really useful :)

  10. Hi,
    To return the class instance in the static method (to chain it), you can use:
    return new self; .

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!