Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

どうも。
最近少し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などでこういったクラスを組んでみると楽しいかもしれません。

morisuke
Vue.js / Laravelが得意。ご連絡はメールかTwitterでどうぞ。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした