Tuesday, 17 September 2013

MVC .. should one database_model contain CRUD for all object_models? Active record vs. registry pattern

MVC .. should one database_model contain CRUD for all object_models?
Active record vs. registry pattern

I'm writing a fairly simple "fact database" in PHP (with Codeigniter ..
but I am trying to get away from the framework internals for learning
purposes), and trying to better my MVC/OOP practices.
Previously I would have done this: a fact model, a user model, a source
model .. and inside each of those models I would place the CRUD logic for
each. So my controllers would have
$this->fact_model->save($fact);
$this->user_model->deactivate($uid);
$this->source_model->get_id($sid);
But after reading more, it seems to make sense to have a separate
persistence model (ie 'database_model'). But then it seems it would have
to contain a full range of CRUD for each type of object, which seems
wasteful to me. I guess I'm looking for how to go to this...
$this->db_m->save(Fact $fact);
$this->db_m->update(User $user);
// .. etc .. but also ..
$this->db_m->get_user_id($uid);
// .. and ..
$htis->db_m->get_all_facts();
Is this heading in the right direction? Do I just end up testing for type
inside the database model and switching when I need to? Or do I extend the
database model for each type of object?
$this->fact_db_m->save(Fact $fact);
$this->fact_db_m->get_all();
$this->source_db_m->get_id($sid);
Or something like this, which I guess is the closest to CIs AR
implementation.
$this->db_m->save('facts', Fact $fact);
$this->db_m->get('user', array('id'=>$uid));
I guess this is a case of "active record vs repository". I understand that
repository is easier to test, and the CRUD logic is separate from the
object data, and that separation makes sense to me. But still.. it means
you have to write a separate repository model for each entity. Is this
right?
BTW - I know Codeigniter has a Database class and uses active record, and
in a way I am just kind of re-creating it with some of those approaches.
I'm just trying to understand things without relying on the framework
internals. Any comments? Is it just a matter of choice?

No comments:

Post a Comment