如何用模型当前状态链接方法?

时间:2017-01-17 20:21:32

标签: php laravel laravel-5 model laravel-5.3

我有一个模型,我得到这样的总订单:

public function total()
{
    $total = $this->subtotal();
    foreach ($this->lineItems as $l) {
        $total += $l->amount;
    }
    return $total;
}

我想添加方法formated(),它会格式化subtotaltotal方法,并返回函数number_format($numberHere, 2)

我希望它是动态的,不像:totalFormatedsubtotalFormated。我想输出这样的格式化值:$order->total()->formated();

我有可能让它工作吗?

2 个答案:

答案 0 :(得分:2)

将总计创建为实例差异

protected $total;

然后将您的功能更改为此

public function total()
{
    $this->total = $this->subtotal();
    foreach ($this->lineItems as $l) {
      $this->total += $l->amount;
    }

    return $this;
}

然后创建格式化函数

public function formated()
{
  return number_format($this->total, 2)
}

现在您可以将功能链接到

$order->total()->formated()

** 已更新 **

您可以在格式化函数中返回总计和小计

public function formated()
{
  return [
      "total" => number_format($this->total, 2), 
      "subtotal" => number_format($this->subtotal, 2)
   ];
}

** **

您可以将一个实例变量用于总计和/或小计。让这个变量命名为myTotals

protected $myTotals;

public function total()
{
    $this->myTotals = $this->subtotal();
    foreach ($this->lineItems as $l) {
      $this->myTotals += $l->amount;
    }

    return $this;
}


public function subTotal()
{
    $this->myTotals = $this->subtotal();
    foreach ($this->lineItems as $l) {
      $this->myTotals += $l->amount;
    }

    return $this;
}

public function formated()
{
    return number_format($this->myTotals, 2)
}

所以在这种情况下你可以打电话

$order->total()->formated() // and this will return the total
$order->subTotal()->formated() // and this will return the subtotal

答案 1 :(得分:0)

您只需将$total保存为属性($this->total += $l->amount),并在total()方法结束时返回您班级的当前实例= $ this < / strong>,基本上:

public function total()
{
    $this->total = $this->subtotal();
    foreach ($this->lineItems as $l) {
        $this->total += $l->amount;
    }

    return $this;
}

现在你的方法返回 Class 本身的实例,这样你就可以调用另一个方法(或该类中的任何其他方法):

public function format()
{
    return number_format($this->total, 2);
}

有了这个,你应该能够&#34;链&#34;你的方法。关键是返回实例

$order->total()->formated()