When creating classes in PHP5, I like to implement what is known as “Method Chaining.” It is the practice of chaining methods onto the back of one another like so:
$object->methodA()->methodB()->methodC();
When would you use this?
It is best practice to use method chaining when you have a series of properties that need to be set. This of course it completely optional but it produces nicer looking code as a result. Anytime I am creating getter and setter functions in my classes I set them up so they can be daisy chained one after the other. Other industries such as Java have been doing this for years in their implementation, and now PHP can do it to (as of PHP5). Let’s look at a real world example:
Example 1.0 - Creating a domain model with Method Chaining support
class Person { public function __construct() { } private $_first = ''; private $_last = ''; private $_email = ''; public function __toString() { return $this->_first . ' ' . $this->_last . ' [' . $this->_email . ']'; } /** * @return boolean */ public function save() { // TODO: Save the data return true; } /** * @return unknown */ public function getEmail () { return $this->_email; } /** * @return unknown */ public function getFirst () { return $this->_first; } /** * @return unknown */ public function getLast () { return $this->_last; } /** * @param unknown_type $_email * @return Person */ public function setEmail ( $_email ) { $this->_email = $_email; return $this; } /** * @param unknown_type $_first * @return Person */ public function setFirst ( $_first ) { $this->_first = $_first; return $this; } /** * @param unknown_type $_last * @return Person */ public function setLast ( $_last ) { $this->_last = $_last; return $this; } } |
Example 1.1 - Using method chaining on the instance
$person = new Person(); $success = $person->setFirst('John') ->setLast('Doe') ->setEmail('john@doe.com') ->save(); echo $success ? 'saved' : 'not saved'; // Output :: // saved |
In this example we populated a domain model “Person” with information and then called save(). In our example save() doesn’t do anyting but in a final class, it could perhaps write the data to a file or database. There are many ActiveRecord solutions out there that implement method chaining to accomplish complex tasks (Zend Framework’s Zend_Db and PHP Doctrine come to mind). ActiveRecords aren’t the only items that method chaining are useful for but it is a common Design Pattern for them. I am sure once you use this technique in your code you will find other uses that meet your needs.