Question

A quick question this time about the M in Mvc.(using codeigniter, but the question is general)

Suppose I have several models that are responsible for accessing several tables in my database, Is it frowned upon making one flexible model that can deal with everything?

specifically in php-codeigniter, for example:

$this->MY_model->getByID($table,$ID)

So this example code can be used to get by ID of any table I want thus saving me time and I'm able to reuse most of my model code.

This of course can be expanded further

$this->MY_model->update($table,$info) as an example.

So my question is, If all of the above is okay, Where is the 'limit' to such operations? Naturally we wouldn't want something really specific in this type of model, like this method:

$this->MY_model->getAllActiveUsers()

My basic approach is this:

Any method that can be used in more than one table should be used in the extended model. Any method that should be used in only one table, should be in it's own model.

Just to be clear i'm not looking for an opinion, But rather wondering what's the standard approach to these issues.(for example, imagine an application with 50 models, should CRUD be written for all 50 of them?)

Thanks in advance!

Was it helpful?

Solution

What you are mulling about is pretty standard operation for most Codeigniter developers. If you are going to be doing a lot of CRUD in the DB, then it makes sense to add a set of generic CRUD methods to your base MY_model and then extend it. If you do a search on Google...you'll likely get results for 100s of people who have setup their own base models including CRUD and other common methods used by most Codeigniter projects...here are just a couple:

https://github.com/jamierumbelow/codeigniter-base-model

https://github.com/jenssegers/CodeIgniter-My-Model

should CRUD be written for all 50 of them?

No. You would extend your base model and use it's generic CRUD methods where they make sense and just override certain properties (table name). Then, if you needed something more specific you could create additional, more granular methods in your new model as you suggested.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top