Методы PHP возвращают массив и все еще могут быть цепными

Я уверен, что это невозможно, но я очень надеюсь, что это станет возможным.

я хочу назвать свои модели таким образом, например

$getAll = models\company::getInstance()->getAll("ID < 4")

который в основном просто

class company extends _ {
private static $instance;
function __construct() {
parent::__construct();
}
public static function getInstance(){
if ( is_null( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
function getAll($where = "") {
// yada yada
$this->return = $return;
return $this;
}

на данный момент я должен добавить переменную $this->return = $return; внутри там и потом по вызову $getAll = models\company::getInstance()->getAll("ID < 4")->show();

function show(){
return $this->return;
}

идея такова, что я могу, например, сделать $getAll = models\company::getInstance()->getAll("ID < 4")->format()->show();

так что вопрос. Есть ли способ сделать это без show () в конце?

В идеале я хочу $getAll = models\company::getInstance()->getAll("ID < 4") вывести массив, и если я делаю $getAll = models\company::getInstance()->getAll("ID < 4")->format() для этого взять массив из getAll() и делать вещи и выводить результат. просто кажется чище, чем положить show() на все

пожалуйста, не распинайте меня за плохую практику. заранее спасибо

0

Решение

Каким-то образом вы должны «пометить» последний звонок, быстрое и грязное решение

class confusing {
private static $instance;

function __construct() {
$this->return = 'nothing';
}

public static function getInstance() {
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}

function getAll($where = "") {
$this->return = 'getAll'.$where;
return $this;
}

function format() {
$this->return = strtoupper($this->return);
return $this;
}

function __call($name,$args) {
$rthis = true;
if ( 'last_'==substr($name,0,5) ) {
$toCall = substr($name,5);
$rthis = false;
}
else {
$toCall = $name;
}
call_user_func_array([$this,$toCall],$args);
return $rthis?$this:$this->return;
}
}

$x = confusing::getInstance()->getAll('x')->last_format();
$y = confusing::getInstance()->last_getAll('y');
$z = confusing::getInstance()->getAll('z');

var_export($x);
var_export($y);
var_export($z);

Или создайте обертку, которая будет исходить

function toResult($x) {
return is_object($x)?$x->show():$x;
}

$getAll = toResult(models\company::getInstance()->getAll("ID <4")->format());

В любом случае вызываемый метод никогда не узнает о цепочках или нет.

0

Другие решения

Нижняя линия. это невозможно.

В моем случае я собираюсь сохранить все мои методы за исключением ->show() который затем вернул бы «результат»

так что даже если я сделаю что-то вроде users->get("1")->remove() он не вернет ни одного сообщения, но выполнит действие. users->get("1")->remove()->show() выведет «Пользователь успешно удален»

Раньше я никогда не беспокоился о цепочках, но это быстро разочаровывает. цепочка определенно, кажется, помогает. начать новый большой проект и попытаться сделать это «лучше» с самого начала

0

Это абсолютно возможно! Вам нужно создать класс, представляющий ResultSet, который можно использовать как обычный массив (путем реализации интерфейсов ArrayAccess, Iterator и Countable) и как объект.

пример

class ResultSet implements ArrayAccess, Countable, Iterator {

private $data = array();
private $position = 0;

public function __construct(array $data=array())
{
$this->data = $data;
}

/* * Implement methods of the Countable interface * */

public function count()
{
return count($this->data);
}

/* * Implement methods of the ArrayAccess interface * */

public function offsetExists($offset)
{
return isset($this->data[$offset]);
}

public function offsetGet($offset)
{
return $this->data[$offset];
}

public function offsetSet($offset, $value)
{
$this->data[$offset] = $value;
}

public function offsetUnset($offset)
{
if( $this->offsetExists($offset) )
unset($this->data[$offset]);
}

/* * Implement methods of the Iterator interface * */

function rewind()
{
$this->position = 0;
}

function current()
{
return $this->data[$this->position];
}

function key()
{
var_dump(__METHOD__);
return $this->position;
}

function next()
{
++$this->position;
}

function valid()
{
return isset($this->data[$this->position]);
}

/* * Implementation of ResultSet specific methods  * */

public function show()
{
//....
}

/**
* @param $in
* @return ResultSet
*/
public function format($in)
{
// do the stuff
return $this;
}

}

Эта реализация позволила бы вызов как -> getAll (‘…’) -> format () -> show (); и в то же время позволить программисту обрабатывать вывод getAll () как массив.

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