Using one crud model for all controllers instead of separate models for each controller

so I saw how usually a model is a representation of a table in a database, as for a user table, it looks something like this:

class user_model { public $id ; public $username ; public $password ; public $email ; public function save(){ $db->query(" insert into `users` (username , email , password ) values ( '$this->username' , '$this->email' , '$this->password' ) "); } public function delete( ){ $db->query(" delete from users where id = $this->id "); } } 

but this process is rather slow, and most models are the basic CRUD operation ... so I use one crud model for almost all of my controllers, for example:

 class crud_model { public function save( $tbl , $data ){ $db->query(" insert into $tbl ( ".explode( ',' , array_keys($data) )." ) values ( ".explode( ',' , $data )." ) "); } public function delete( $tbl , $data ){ $db->query(" delete from $tbl where $data['column'] = $data['val'] "); } } 

Please note that this is a very simplified version of my model and basically it is nothing like the source code (im using active writing in the source code and it can handle complex scripts), so ignore the syntax and technical errors.

so I want to know if there is a problem with this approach? Am I missing something?

What is the point of having many models when you can get by with one CRUD model .... it just seems like time

+5
source share
1 answer

Your approach is not necessarily the wrong one. As programmers, we like everything to be consistent, so when you need to make changes to your code, you don’t need to worry about one table model working differently from another table model. We are also lazy (in a good way), so you want to write your CRUD class once and use it everywhere. You have this part with the idea of ​​one class.

However, if you take your CRUD class and then inherit all your table models, you will get the benefits of writing code once, plus if you need to do something with a table that goes beyond your base CRUD code, which you can easy to override or add to functionality in a class of child tables.

In terms of a model availability template for presenting your tables with your current approach, you really cannot represent individual tables with a common CRUD class. In model classes, there are often additional class properties specific to the presented table. This allows you to design classes so that if you need to reuse them, the developer better understands the underlying data structure. Take a look at your example User class in the original question. This class has properties such as $id , $username and $password . The developer can look at this and know exactly what is needed to create a new user.

+2
source

Source: https://habr.com/ru/post/1239895/


All Articles