Метод, соединяющий функцию get для возврата определенных $ this свойств

Я хочу иметь возможность использовать объект, как показано ниже, для получения новых заказов и новых счетов. Я чувствую, что он наиболее читабелен, но у меня возникают проблемы при написании класса 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?
}

}

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();
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 метод.

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector