【问题标题】:Method chaining a get function to return specific $this properties链接 get 函数以返回特定 $this 属性的方法
【发布时间】:2018-08-09 02:28:19
【问题描述】:

我希望能够使用如下所示的对象来检索新订单和新发票。我觉得它的可读性最强,但我在编写 PHP 类以这种方式工作时遇到了麻烦。

$amazon = new Amazon();
$amazon->orders('New')->get();
$amazon->invoices('New')->get();

在我的 PHP 类中,我的 get() 方法如何区分是退货还是退货?

<?php

namespace App\Vendors;

class Amazon
{
    private $api_key;
    public $orders;
    public $invoices;

    public function __construct()
    {
        $this->api_key = config('api.key.amazon');
    }

    public function orders($status = null)
    {
        $this->orders = 'orders123';

        return $this;
    }

    public function invoices($status = null)
    {
        $this->invoices = 'invoices123';

        return $this;
    }

    public function get()
    {
        // what is the best way to return order or invoice property
        // when method is chained?
    }

}

【问题讨论】:

  • 你能在这里展示你想要实现的类吗?
  • @PubuduJayawardana 添加了

标签: php api class methods chaining


【解决方案1】:

有几种方法,如果您希望它是动态的并且不在方法中执行任何逻辑,请使用类似__call

<?php
class Amazon {
    public $type;
    public $method;

    public function get()
    {
        // do logic
        // ...

        return 'Fetching: '.$this->method.' ['.$this->type.']';
    }

    public function __call($method, $type)
    {
        $this->method = $method;
        $this->type = $type[0];

        return $this;
    }

}

$amazon = new Amazon();

echo $amazon->orders('New')->get();
echo $amazon->invoices('New')->get();

如果您想在方法中执行逻辑,请执行以下操作:

<?php
class Amazon {
    public $type;
    public $method;

    public function get()
    {
        return 'Fetching: '.$this->method.' ['.$this->type.']';
    }

    public function orders($type)
    {
        $this->method = 'orders';
        $this->type = $type;

        // do logic
        // ...

        return $this;
    }

    public function invoices($type)
    {
        $this->method = 'invoices';
        $this->type = $type;

        // do logic
        // ...

        return $this;
    }
}

$amazon = new Amazon();

echo $amazon->orders('New')->get();
echo $amazon->invoices('New')->get();

【讨论】:

    【解决方案2】:

    由于订单和发票都是设置方法,我建议如下:

    public function get(array $elements)
    {
        $result = [];
        foreach($elements as $element) {
            $result[$element] = $this->$element;
        }
    
        return $result;
    }
    

    所以,你可以调用get方法:

    $amazon = new Amazon();
    $amazon->orders('New')->invoices('New')->get(['orders', 'invoices']);
    

    ** 您需要在get 方法中验证元素的可用性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-27
      • 1970-01-01
      • 2012-01-22
      • 2012-12-24
      • 2021-08-20
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多