LoginSignup
61
60

More than 5 years have passed since last update.

PHPにおけるメソッドチェーンの構築

Last updated at Posted at 2014-01-09

どうも。
最近少しRailsに浮気していたmorisukeです。

元鞘に収まりLaravel4でガリガリ組んでいたら自分でもやってみたくなったので、
PHPでのメソッドチェーンの組み方を復習してみました。

chain.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->option = $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;
  }
}
useExample1
$chain = new Chain();

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

$total_amount = $chain->get();
echo $total_amount;
// 375
useExample2 (PHP5.4以降)
$total_amount = (new Chain)
  ->setPrice(100)
  ->setQuantity(5)
  ->setOption([
    'tax'      => '0.05',
    'discount' => '150'
  ])
  ->get();

echo $total_amount;
// 375

setPrice()やsetQuantity()で return $this; をしているのがチェーンの要。
$thisは自分自身を表すので返り値は必ずChainインスタンスを取ります。
そのため返り値に対し直接メソッドを呼び出しても大丈夫なわけです。

せっかくLaravel4というメソッドチェーンにあふれた環境でコーディングするのですから、
共通Serviceなどでこういったクラスを組んでみると楽しいかもしれません。

61
60
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
61
60