18
First of all, I know that I should not go out making classes with various static methods but in this case that I bring here, I do not understand why it can be considered bad practice.
Let’s say I have a MVC structure, in my model, I have all the respective methods of my CRUD, create, read, update and delete. However, I always make a static method called list, this in turn, can return a Collection (array even in the case in php) with several objects of the specific model and there, for each object, I have your CRUD methods. I see no problem in listing to be static, since it will not interact directly with anything else in my class.
I did a lot of research on the subject and I couldn’t find anything to change my mind, so I wanted to bring this discussion here.
Unless you have misunderstood... Why does the list method return multiple objects? What application do you make of this?
– Papa Charlie
For example, I have a Person Class. I can insert, read, update and delete it. But and when I want to list for example, all the People I have. Present a list to the user. In this case, I have the practice of using a static method, because I’m not going to interact directly with other methods or attributes of the Person class, but still, I’m doing something related to Person, so, why not, use a static method, that, instantiating one person for each line that my query returns and I return that list
– Mario de M. Barros Neto
Related: What is the function of a static method?
– Marcelo de Andrade
I saw no problem in this approach, it may even be practical. I may be wrong, but the Laravel (Laravel.com) framework does something similar for some methods.
– Fábio Jânio
When we think that a static method would be a "class method" and would be executed without needing an instance of it to list objects, I don’t think I see any problem in this approach. It even makes a certain sense to me by analyzing the concepts themselves. Only one question arose that is related to the connection with the Database in this static method: how is this connection made? All programmed in the static method? I imagine so because it is static.
– Pantoja
I believe there is no mistake in using static methods for this, but it seems to me that your class is more responsible than just a model. This is common when using some Activerecord type Orm as the Eloquent of the Laravel. To avoid this type of approach, it is common to implement the Pattern Repository, and decouple the integration model with the BD.
– Jhonny Freire