What is Method Chaining?
Method Chaining allows you to do multiple calls on the same object without explicitly typing the objects name.
For example, you could type this:
Instead of this:
This works by having each method return a reference to the called object.
Advantages to using Method Chaining
Although Method Chaining doesn’t typically bring any significant performance gains, it brings many advantages to your source code.
One obvious advantage, you will write less code.
By adopting Method Chaining and proper indentation techniques you will also find yourself writing cleaner code.
Your code will be more expressive and easier to understand.
Take for example a situation where you’d like to set a cookie for a specific domain.
Here is what it would look like with PHP’s setcookie function:
Personally, I believe there are a few readability issues with the above code.
First, not everyone knows the exact order of the arguments to setcookie. I understand that most IDE’s help with this, but if someone quickly glances at the code, he will have to think a few seconds to figure out what argument is being set to “.cakemail.com”.
Also, it’s a shame that you need to specify “null” for the fourth argument because you want to set the $domain argument.
What if the setcookie function was a chainable object?
Setting a cookie using the chainable Cookie object has several notable advantages:
- Every argument is properly labeled. At a glance, you can see that the domain is being set to “.cakemail.com” and the expire is being set to “0”.
- Adding another argument (for instance setting the $httponly argument to true) is much easier. There’s no need to look up the setcookie function to find out that it’s the 7th parameter and there’s no need to specify null values for the arguments before it.
Removing a cookie is just as easy. Here’s the standard PHP way:
And the chaining way:
Quick note when implementing method chaining
Most editors will not be able to provide typing auto-complete after the first method call. This is because the editor is not aware of what is being returned by the method.
Properly documenting the code should fix this in most editors.
For those who are interested, the source code of this article are available on GitHub:
Method Chaining is the core concept behind Fluent Interface. If you are interested, you can read more about it over on Wikipedia: http://en.wikipedia.org/wiki/Fluent_interface
By Christian Joudrey, CakeMail’s Lead Programmer. You can follow Christian on twitter @cjoudrey.