klon
klon

Reputation: 45

codeigniter best practice - multiple models

Just a quick question about best practice in MVC development.

Let's say that I've got two controllers (cont1, cont2), each of which uses a separate model, model1 & model2.

All files are complex; the models contain dozens of methods.

Say, I finished developing the first controller and I'm in the middle of work on the second one. I need to create a method in model2 which will be exactly the same as one of methods in model1. It's only a tiny method, to get, for example, a list of categories of some sort.

What's the best approach of work - should I duplicate the method and include it in my model2, or should I retrieve it from model1?

The reasonable thing to do would be to get it from model1, but I don't know if that would affect the execution time, as it would have to load both models.

I would be grateful for some feedback

Upvotes: 4

Views: 1937

Answers (3)

Mike Funk
Mike Funk

Reputation: 363

I've run into the same situation. What I do is load the codeigniter object by reference in every model. Then I can load other models, libraries, helpers, even config items into my models. It helps keep model code out of the controller, and I'd consider it a best practice. Always keep it DRY (Don't Repeat Yourself).

Upvotes: 0

Jack McDade
Jack McDade

Reputation: 669

Maybe what you really need is a third model. If you have a method that's being used in many/all of your models, it really may be a unique data set that would warrant it's own attention. Also, you'll prevent having to load multiple "large" models, and instead have 1 large and 1 tiny model.

Upvotes: 1

Justin Ethier
Justin Ethier

Reputation: 134255

Loading a second model will not have a noticeable impact on execution time. This is probably the way to go.

Also, each model should encapsulate data logic for a specific 'object'. You can think of each model almost like a database table. So you probably do not really want to have the same method in two different places - and if you do, you may want to consider creating a plugin.

Upvotes: 3

Related Questions