Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am using codeigniter, and have found myself in a similar situation where I have repeated Model methods. I am creating a Model per Controller. But I would creating a Model per database table be considered good practice? That way methods aren't written twice.

Instead of Model per Controller or Several small Models that are shared.

Example if I have a model method get_user($user_id) I could write it on users_models.php ...

One of the downsides I see of this is that I might have to call several models, rather than just controllername_models.php .

Could loading several models where several methods might not be used from a controller affect performance and speed? What could be the best way to tackle this down?

Note: There are similar question, but they do not cover the ground of Model per database table.

share|improve this question
add comment

2 Answers

I's say that a model per table is just recreating your database in a class structure. It is known as a anemic model and considered an anti-pattern. That is because classes are intended to have both data and behaviour. If you restrict your models to a single table, where do you put the code (behaviour) that needs to deal with data and behaviour from multiple tables? Your controllers would then need models that use one or more of these "table" models... So, apart from in the most basic of apps, you gain little if anything from this approach.

share|improve this answer
add comment

In general you should create your models not per table or per controller but per business object. Sometimes it maybe a 1:1 relationship with your tables structure or with your controllers, but not necessary.

In your example you may have one users_model class that is called from several controllers. This is fine and sometimes even desirable. However in most cases the users_model class will get its data from several tables.
For example, last_login_date property of the users_model class can (not must) be obtained from a separate user_audit table that has one-to-many relationship with the main users table.

And I would say if you have one SQL table per business object then it is most likely that your database structure is not normalized.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.