以下是我个人实施模型的方式。我将使用一个真实的例子:我的User 模型。
每当我创建一个模型时,我都会使用两个文件和两个类:模型本身(例如Application_Model_User)和一个映射器对象(例如Application_Model_UserMapper)。模型本身显然包含数据、保存、删除、修改等方法。映射器对象包含获取模型对象、查找对象等方法。
这是 User 模型的前几行:
class Application_Model_User {
protected $_id;
protected $_name;
protected $_passHash;
protected $_role;
protected $_fullName;
protected $_email;
protected $_created;
protected $_salt;
// End protected properties
对于每个属性,我都有一个 getter 和 setter 方法。 id 的示例:
/* id */
public function getId() {
return $this->_id;
}
public function setId($value) {
$this->_id = (int) $value;
return $this;
}
我还使用一些标准的“魔术方法”来公开公共 getter 和 setter(在每个模型的底部):
public function __set($name, $value) {
$method = 'set' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid user property');
}
$this->$method($value);
}
public function __get($name) {
$method = 'get' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid user property');
}
return $this->$method();
}
public function setOptions(array $options) {
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
例如save方法:
我在save() 方法内部进行验证,当信息验证失败时使用异常。
public function save() {
// Validate username
if (preg_match("/^[a-zA-Z](\w{6,15})$/", $this->_name) === 0) {
throw new Application_Exception_UserInfoInvalid();
}
// etc.
$db = Zend_Registry::get("db");
// Below, I would check if $this->_id is null. If it is, then we need to "insert" the data into the database. If it isn't, we need to "update" the data. Use $db->insert() or $db->update(). If $this->_id is null, I might also initialize some fields like 'created' or 'salt'.
}
对于mapper对象,我至少有两个方法:一个是返回查询对象选择对象的方法,一个是执行查询、初始化并返回对象的方法。我使用它是为了在控制器中操作查询以进行排序和过滤。
编辑
就像我在我的 cmets 中所说,这篇文章:http://weierophinney.net/matthew/archives/202-Model-Infrastructure.html 是我当前模型实现的灵感。
更多选项
您也可以使用Zend_Form 进行验证,而不是自己滚动:http://weierophinney.net/matthew/archives/200-Using-Zend_Form-in-Your-Models.html。我个人不喜欢这个选项,因为我认为Zend_Form 使用起来很尴尬并且难以精确控制。
当大多数人第一次学习 Zend Framework 时,他们会学习继承 Zend_Db 相关类。这里有一篇文章证明了这一点:http://akrabat.com/zend-framework/on-models-in-a-zend-framework-application/
我提到我不喜欢这样做。以下是一些原因:
- 很难创建涉及派生/计算字段(即从其他表填充的数据)的模型
- 我发现无法合并访问控制(从我的数据库中填充)
- 我喜欢完全控制我的模型
编辑 2
对于您的第二个示例:您可以为此使用Zend_Paginator。我提到过,在您的包装器中,您创建了一个方法,该方法返回用于选择对象的数据库查询对象。这是我的简化但有效的用户映射器:
class Application_Model_UserMapper {
public function generateSelect() {
$db = Zend_Registry::get("db");
$selectWhat = array(
"users_id",
"name",
"role",
"full_name",
"email",
"DATE_FORMAT(created, '%M %e, %Y at %l:%i:%s %p') as created",
"salt",
"passhash"
);
return $db->select()->from(array("u" => "users"), $selectWhat);
}
public function fetchFromSelect($select) {
$rows = $select->query()->fetchAll();
$results = array();
foreach ($rows as $row) {
$user = new Application_Model_User();
$user->setOptions(array(
"id" => $row["users_id"],
"name" => $row["name"],
"role" => $row["role"],
"fullName" => $row["full_name"],
"email" => $row["email"],
"created" => $row["created"],
"salt" => $row["salt"],
"passHash" => $row["passhash"]
));
$results[] = $user;
}
return $results;
}
}
为了处理分页器,我编写了一个自定义分页器插件并将其保存到library/Application/Paginator/Adapter/Users.php。确保您在 application.ini 中正确设置了 appnamespace 和 autoloaderNamespaces[]。这是插件:
class Application_Paginator_Adapter_Users extends Zend_Paginator_Adapter_DbSelect {
public function getItems($offset, $itemCountPerPage) {
// Simply inject the limit clause and return the result set
$this->_select->limit($itemCountPerPage, $offset);
$userMapper = new Application_Model_UserMapper();
return $userMapper->fetchFromSelect($this->_select);
}
}
在我的控制器中:
// Get the base select statement
$userMapper = new Application_Model_UserMapper();
$select = $userMapper->generateSelect();
// Create our custom paginator instance
$paginator = new Zend_Paginator(new Application_Paginator_Adapter_Users($select));
// Set the current page of results and per page count
$paginator->setCurrentPageNumber($this->_request->getParam("page"));
$paginator->setItemCountPerPage(25);
$this->view->usersPaginator = $paginator;
然后在你的视图脚本中渲染分页器。