Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Archive for December 27th, 2008

Dec 27 2008

Method Chaining in PHP

Published by Prajwal Tuladhar under PHP

Make modifier methods return the host object so that multiple modifiers can be invoked in a single expression. - Martin Fowler [article]

In simple terms method chaining is the way of calling a sequence of class methods where each object returns the same host object for further modification. This approach is more used by JAVA and .NET developers (as I have seen). After having a quick look at various PHP frameworks like Zend, CodeIgniter and Cake, it seems like they do support method chaining and I really love to use method chaining when possible. Enabling method chaining is quite similar in PHP as it is in C# and JAVA. By the use of $this, method chaining can be enabled for any class.


<?php
	class HardDrive
	{
		private $_capacity;
		private $_isExternal;
		private $_speed;

		//Getters and setters for _capacity
		function getCapacity()	{
			return $this->_capacity;
		}

		function setCapacity($capacity)	{
			$this->_capacity = $capacity;
			return $this;
		}

		//Getters and Setters  for _isExternal
		function getIsExternal()	{
			return $this->_isExternal;
		}

		function setIsExternal($isExternal)	{
			$this->_isExternal = $isExternal;
			return $this;
		}

		//Gettter and setter for speed
		function getSpeed()	{
			return $this->_speed;
		}

		function setSpeed($speed)	{
			$this->_speed = $speed;
			return $this;
		}
	}
?>

Using Method Chaining for above Class


<?php
	$hardDrive = new HardDrive();
	$hardDrive
		->setCapacity(200)
		->setIsExternal(false)
		->setSpeed(7200);
?>

 

…or using traditional way


<?php
	$hardDrive = new HardDrive();
	$hardDrive->setCapacity(200);
	$hardDrive->setIsExternal(false);
	$hardDrive->setSpeed(7200);
?>

I have seen people who really hates method chaining and also seen people that use this approach a lot. And luckily or unluckily I am also kinda supporter of method chaining. So, if you are like me I hope you want to enable method chaining in your class as well and as you saw it’s very very simple.

And finally, some considerations you need to know. I don’t think method chaining is possible in PHP 4 (but who cares about PHP 4, coz it’s kinda RIP :) ). The biggest problem with PHP method chaining I have felt is that IDE like Eclipse really don’t provide auto-complete feature :(


Comments

RSS Feed
Subscribe by email
Follow me @ Twitter