I'm designing a web application with CodeIgniter (but I think the question applies generally to the MVC pattern in web applications).
When I design the model class for some database entity (say, a BlogEntry
for illustration), I basically have two choices:
The "classic OOP" approach would be, to let the class represent the entity, i.e. one instance of the class is a BlogEntry. In CodeIgniter, this would lead to code like
class Blogentry extends CI_Model {
function load($id) {
// Access database
$this->id = $dbresult.id;
$this->title = $dbresult.title;
$this->author = $dbresult.author;
}
}
To get access to some blog entry, I would do a $this->load->model('blogentry');
, call $this->blogentry->load($id)
and then work with the model class instance.
The other approach, which I've seen frequently in the wild, is to let the model return the entity in some data structure. In code:
class Blogentry extends CI_Model {
function get_entry($id) {
// Access database, yielding $dbresult
return $dbresult;
}
With this I would write
$this->load->model('blogentry');
$the_entry = $this->blogentry->get_entry($id);
in the controller and work with $the_entry
. In this second case, the class is more like a factory or builder class.
Is any of these two approaches considered the "right way" of doing M in MVC? I think, I've seen the second approach more often, but I didn't look at that many MVC-Webapps. Any thoughts of why the first or the second approach might be more appropriate?