メソッドチェーン

メソッドチェーンとは、メソッドをアロー演算子で複数つなぎ、複数のメソッドを一度に行うことです。

サンプルを見てみましょう。

<?php

class Product
{
	private $price = 100;

	public function getPrice()
	{
		return $this->price;
	}
}

class Cart
{
	private $products = array();

	public function add($product)
	{
		$this->products[] = $product;
	}

	public function get($index)
	{
		return $this->products[$index];
	}
}

$cart = new Cart();
$product = new Product();
$cart->add($product);

$prd = $cart->get(0);
$price = $prd->getPrice();

$price = $cart->get(0)->getPrice();

?>
<?php

class Date
{
	private $_timestamp;

	public function __construct()
	{
		$this->_timestamp = time();
	}

	public function addDay($days)
	{
		if (true == preg_match('/^[0-9]+$/', $days)){
			$str = sprintf('+%s day', $days);
			$this->_timstamp = strtotime($str, $this->_timestamp);
		}
	}

	public function format($format)
	{
		return date($format, $this->_timestamp);
	}
}

$date = new Date();
$date->addDay(3);
$fmt = $date->format('Y/m/d H:i');
var_dump($fmt);

?>
<?php

class Chain {
	protected $price;
	protected $quantity;
	protected $option;

	public function setPrice($price){
		$this->price = $price;
		return $this;
	}	

	public function setQuantity($quantity){
		$this->quantity = $quantity;
		return $this;
	}

	public function setOption($option){
		$this->optioin = $option;
		return $this;
	}

	public function get(){
		$amount = $this->price * $this->quantity;
		foreach ($this->option as $key => $val){
			if ($key == 'tax') $amount -= ceil($amount * $val);
			elseif($key == 'discount') $amount -= $val;
		}

		return $amount;
	}
}

$chain = new Chain();
$chain
 ->setPrice(100)
 ->setQuantity(5)
 ->setOption(array(
 	'tax' => '0.05',
 	'discount' => '150'
 	));
 $total_amount = $chain->get();
 echo $total_amount;

?>