yiisoft / data

Data providers

Home Page:https://www.yiiframework.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Allow building criteria with arrays

samdark opened this issue · comments

Syntax could be something like:

$filter = $aaa->where([
  ['and', 'id', '>', 3],
  ['and', ['or', ['temperature', '<', 10], ['temperature', '>', 30]] ],
  ['and', 'name', like', '%agent%'],
];

See https://yiiframework.ru/forum/viewtopic.php?f=39&t=52964

There already is "filter to array" transformation in IterableDataReader:

$filter = null;
if ($this->filter !== null) {
    $filter = $this->filter->toArray();
}

Could be replaced with

$filter = $this->filter instanceof FilterInterface
    ? $this->filter->toArray()
    : $this->filter;

So well-formed filter will work properly. But there will be problems with incorrect filters (kind of ['and', 'id', '>']) and will require some extra validation.

UPD:
I thought and IMHO that should not be done.
In Yii2, newbies have always had problems setting conditions for where. Just look at the popularity of the questions "Operator '{operator}' requires {N} operands". And even more experienced often have to google the correct order of operands. When using objects at the same time, the correctness of the constructed $filter array is guaranteed, and the author of the code sees the types and names of constructor parameters so as not to confuse.

@pchapl Yes, objects are better. But it seems here the speech about that there was an opportunity to use arrays.

It is more about working with a special filter string that comes from request like it's done for sorting.

In Yii 2 REST APIs there was ability to specify filtering as JSON.

Requirements are:

  1. It should be as short as possible.
  2. It should be readable.
  3. Some filters could be disabled for some fields (tricky part).

Overall, it can be done with a separate component so could be safely postponed or done in another package such as GridView.

$filter = $aaa->where([
  ['and', 'id', '>', 3],
  ['and', ['or', ['temperature', '<', 10], ['temperature', '>', 30]] ],
  ['and', 'name', like', '%agent%'],
];

I would limit the use of this to simplify code.

$filter = new All()->withArray([
  ['<', 'id', 22],
  ['or',
    ['>', 'apple', 33],
    ['!=', 'peach', 44], 
  ]
])

$filter = new Any(
  new All(new Equals(), ...),
  new All()->withArray([...]),
)

Arrays would be limited to the All class, this method would allow all kinds of use. The All class is working on arrays, so much easier code is created.

All or Any. Yes, good idea.