M
M
Max Ba2018-03-13 10:34:05
PHP
Max Ba, 2018-03-13 10:34:05

How to correctly implement the list output method?

Hello guys. I create a new class. It has a method for displaying an array of data from the database. Sometimes you need to display one line, sometimes all, and sometimes you need to specify some special parameters (pre-written). I do this: So far, the array only accepts: $options['id'] Question: 1 ) Is it true that I built the data output logic in one method, that is, we can either specify an ID or not, and then all records will be displayed, or it was necessary create a separate method that displays only one record? 2 . Have I named the getAll method correctly. because it translates as "to get everything." And I will shorten it to get, in my opinion it’s not the same meaning already. How are such methods generally called PSR?
public function getAll($options = []){}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
Lander, 2018-03-13
@phpcoder81

Why not do this?:

...
    public function select($conditions = [])
    {
        ...
    }

    public function selectAll()
    {
        return $this->select([]);
    }

    public function selectOne($id)
    {
        $result = $this->select(['id' => $id]);
        return count($result)
            ? current($result)
            : null;
    }
    ...

M
Maxim Fedorov, 2018-03-13
@qonand

1. To search for one record by ID, it would be logical and convenient to implement a separate method, for example, some kind of findOne($id). Regarding the getAll method - what does the Options array contain? A set of parameters by which records should be selected? if so, then passing it as an array is not a good practice, it's better to make some object to the criterion. Yes, and the name $options is not very successful ...
2. It is better to name such methods, for example, find ()

D
Denis, 2018-03-13
@sidni

well, there are different methods, some use the name get how to take i.e. either data or error + methods prefixed with find where either data or false.
And in your case, you can do whatever you like with findAll, findById, findByConditions, etc.
PS read about ORM

A
Andreo, 2018-03-13
@chupacabramiamor

Do not use a bunch of functionality in one method. Each method must do a strictly defined function and return a value of a strictly defined type, otherwise surprises will pop up when processing such "universal functions".
Use separate methods to display a single record and a list.
For naming methods, look at the standards, but do not bother - without fanaticism. The main thing in the naming of variables and functions was clear what it is, it is desirable to follow the syntax of the English language, and be sure to follow a single naming rule within the project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question