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

时间:2018-08-09 02:28:19

标签: php api class methods chaining

我希望能够使用如下所示的对象来检索新订单和新发票。我觉得它最具可读性,但是我在编写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?
    }

}

2 个答案:

答案 0 :(得分:0)

由于订单和发票是固定方法,因此建议执行以下操作:

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

答案 1 :(得分:0)

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