我正在设计一个使用
CodeIgniter的Web应用程序(但我认为这个问题一般适用于Web应用程序中的
MVC模式).
当我为一些数据库实体设计模型类(例如,一个BlogEntry为例)时,我基本上有两个选择:
“经典的OOP”方法是让类代表实体,即该类的一个实例是一个BlogEntry.在CodeIgniter中,这将导致代码
class Blogentry extends CI_Model {
function load($id) {
// Access database
$this->id = $dbresult.id;
$this->title = $dbresult.title;
$this->author = $dbresult.author;
}
}
要访问某些博客条目,我将执行一个$this-> load->模型(‘blogentry’);调用$this-> blogentry-> load($id),然后使用模型类实例.
我经常在野外看到的另一种方法是让模型在一些数据结构中返回实体.在代码中:
class Blogentry extends CI_Model {
function get_entry($id) {
// Access database,yielding $dbresult
return $dbresult;
}
有了这个我会写
$this->load->model('blogentry');
$the_entry = $this->blogentry->get_entry($id);
在控制器中并与$the_entry一起工作.在第二种情况下,该类更像是factory或builder类.
这两种方法中有哪一种被认为是在MVC中做M的“正确方法”?我认为,我经常看到第二种方法,但是我并没有看到很多MVC-Webapps.任何想法,为什么第一种或第二种方法可能更合适?