链接 get 函数以返回特定$this属性的方法



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

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

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

<?php
namespace AppVendors;
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?
    }
}

有几种方法,如果您希望它是动态的并且不要在方法中执行任何逻辑,请使用类似 __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();

由于订单和发票是设置方法,我建议执行以下操作:

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方法中验证元素的可用性。

最新更新