John Squibb
Class Method Chaining in PHP
When you call a class method in PHP, quite often, you expect to get back a value. This value may be a boolean, a string, an array, an Exception object, whatever. Perhaps you use this return to determine whether an error happened, or maybe to store a cleaned value in the database. A neat technique is to return a reference to the object whose method you just called, so that you can reuse the same object without having to explicitly call it again. This is called chaining.
To chain a class method, you simply have to return the $this variable rather than your ordinary return value. By doing so, you can immediately use the return from your method call to invoke another call. Take the following code for example (assume the class used exists somewhere):
<?php
$class = new MyUserClass;
$class->authenticate('username', 'p4ssw0rd');
$class->log_attempt();
$class->redirect();
In the above sample, we've instantiated a class for handling various user tasks, and have made a few calls. What sticks out about this code snippet, is that we've made several calls to methods of the same object, and we haven't used a single return value for anything. This class is begging to be chained! To chain these calls, the class methods would have to look something like:
public function authenticate($username, $password)
{
logic here...
... .. .
return $this;
}
public function log_attempt()
{
logic here...
... .. .
return $this;
}
With this structure, we can now chain our method calls together like so:
$class->authenticate('username', 'p4ssw0rd')->log_attempt()->redirect();
Since the authenticate method returns a reference to its class, which happens to also be stored by reference in the $class variable, calling $class->authenticate('username', 'p4ssw0rd')->log_attempt() is the same as calling $class->log_attempt() above. Since log_attempt returns a reference to its class as well, you can continue to chain more method calls. The process only stops once you have reached a method that does not return a reference to itself. If you reach a method that returns something else and you attempt to chain another method call, you may encounter an error or get something you didn't expect back.
One of the best chained method implementations I've seen to date is the Kohana Framework's Database Query Builder class. Consider the following method chain:
$result = $this->db->from('users')->select('username')->where('id',1)->get();
This method chain set demonstrates the Query Builder's power to, well, build queries! Each method call builds the query for its namesake's SQL counterpart. The sample above would generate the following query.
SELECT username FROM users WHERE id = 1;
The final call, get(), executes the query and returns the result. Pretty snazzy eh? The best part about the Query Builder class, is that the sequence can be called in most any order, within reason. Since each of the methods returns a $this, the above sample could be reworked to the following:
$result = $this->db->select('username')->from('users')->where('id',1)->get();
Since PHP is pretty forgiving when it comes to whitespace, you can make your code a bit easier to read by adding some newlines to your chains. Consider the user code from earlier in this tutorial:
$class
->authenticate('username', 'p4ssw0rd')
->log_attempt()
->redirect();
Method chains are a nice way to simplify the use of multiple methods for all types of classes, especially for classes like the Query Builder above. The downside is that you lose your return values, so this technique may not be appropriate for all classes and situations. Experiment with them some more, and when you feel confident, check out the Chainable Interface Tutorial.
More Tutorials
You can check out more tutorials in the tutorials section.
Suggested Reading
PHP 6 and MySQL 5
by Larry Ullman
I keep a copy of Visual Quickpro Guide, PHP 6 and MySQL 5 on my shelf to loan out to new PHP developers that have done little more than dabble in PHP for their personal website, and so on.
I literally wore an older edition of this book out by reading it from cover-to-cover, re-reading it, and carrying it around with me everywhere I went.
It was like my first guitar, I used the heck out of it! As the name implies, this book is designed to get you going. Larry Ullman does a great job of teaching the basics so that you can get a dynamyic website
talking to a MySQL database, complete with forms, sessions, cookies, security mechanisms, and on and on...If you don't know PHP, but are looking for a great way to dive in, buy this book.
Suggested Reading
Linux in a Nutshell
by Ellen Siever et al.
This book is essentially man in paper form.
It is a thick book of Linux CLI goodness. It provides an alphabetized guide of all the popular command line utilites that Linux users have come to know and love.
Suggested Reading
Essential PHP Security
by Chris Shifflet
Essential PHP Security is the one-stop PHP security handbook. PHP security Guru, Chis Shifflet, provides the reader with all the steps necessary to bolster the security of any web application. This book does a great job of breaking common security pitfalls into easy-to-digest explanations that will provide insight to any PHP coder, novice to expert. This is a must-have for web application developers. Don't leave home without it!
Suggested Reading
PHP Objects, Patterns, and Practice
by Matt Zandstra
Apress' PHP Objects, Patterns, and Practice is great for beginners and veterans alike.
The first several chapters focus entirely on the foundations of Object-Oriented PHP (OOPhp), while later chapters teach various patterns such as the Factory, Singleton, Observer, and more.
The author, Matt Zandstra, places major emphasis on good programming habits and strives to teach as many enterprise level practices as space allows.
The last chapters introduce the reader to a series of productivity tools which cover version control, documentation, automated builds, and unit testing.
This text will complement any OOPhp application developer, and I recommend it to anyone looking to dive in, or a seasoned OOPhp developer looking to pick up some new tricks and tools.
Tags: PHP, Class, Method Chaining
Short URL: http://sqb.in/o2tH