Since the introduction of PHP 5 and it’s better OO capabilities it is possible to use method chaining. In most modern frameworks, like Zend Framework‘s Zend_Mail for example, it’s widely used.

An example of method chaining from the Zend Framework documentation for the Zend_Mail component looks like this:

$mail = new Zend_Mail();
$mail->setBodyText('This is the content of the mail.')
     ->setFrom('somebody@example.com', 'Some Sender')
     ->addTo('somebody_else@example.com', 'Some Recipient')
     ->setSubject('My own subject')
     ->send();

The code above can also be written like below, without method chaining:

$mail = new Zend_Mail();
$mail->setBodyText('This is the content of the mail.');
$mail->setFrom('somebody@example.com', 'Some Sender');
$mail->addTo('somebody_else@example.com', 'Some Recipient');
$mail->setSubject('My own subject');
$mail->send();

It depends on your likings of which method you want to use, but you can extend your methods with the chaining way without harming the traditional way so in the end the programmer can decide the method he desires. If you want to make the methods ready for it the method simply needs to return the object itself, like so:

public function foo() {
    // ... do something here ...
    return $this;
}

I’ve highlighted line 3 where the magic applies. If you had foo(), bar(), baz() and bat() methods you could then do this:

$myClass->foo()->bar()->baz()->bat();

You may not want or need to do this in any of your code, but the possibility is there if you or any colleague wants to.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Furl
  • LinkedIn
  • StumbleUpon
  • Technorati
  • TwitThis
  • NuJIJ