問題描述
您在 Zend 框架中實現(xiàn)模型的方式有哪些?
What are some of the ways you have implemented models in the Zend Framework?
我已經(jīng)看到了基本的 class User extends Zend_Db_Table_Abstract
然后在你的控制器中調(diào)用它:
I have seen the basic class User extends Zend_Db_Table_Abstract
and then putting calls to that in your controllers:
$foo = 新用戶;
$foo->fetchAll()
但是更復雜的用途呢?文檔的快速入門部分提供了這樣一個示例,但我仍然覺得我沒有得到 Zend Framework 中模型的最佳使用"示例.有什么有趣的實現(xiàn)嗎?
but what about more sophisticated uses? The Quickstart section of the documentation offers such an example but I still feel like I'm not getting a "best use" example for models in Zend Framework. Any interesting implementations out there?
我應該澄清(回應 CMS 的評論)...我知道做更復雜的選擇.我對模型概念的整體方法和其他人如何實現(xiàn)它們的具體示例感興趣(基本上,手冊遺漏的內(nèi)容以及基本操作方法所掩蓋的內(nèi)容)
I should clarify (in response to CMS's comment)... I know about doing more complicated selects. I was interested in overall approaches to the Model concept and concrete examples of how others have implemented them (basically, the stuff the manual leaves out and the stuff that basic how-to's gloss over)
推薦答案
我個人對 Zend_Db_Table_Abstract
和 Zend_Db_Table_Row_Abstract
進行了子類化.我的代碼和你的代碼之間的主要區(qū)別在于,明確地將 Zend_Db_Table_Abstract
的子類視為表",將 Zend_Db_Table_Row_Abstract
的子類視為行".我很少在控制器中看到直接調(diào)用選擇對象、SQL 或內(nèi)置 ZF 數(shù)據(jù)庫方法.我嘗試隱藏請求特定記錄以調(diào)用 Zend_Db_Table_Abstract
后面的邏輯,如下所示:
I personally subclass both Zend_Db_Table_Abstract
and Zend_Db_Table_Row_Abstract
. The main difference between my code and yours is that explicitly treat the subclass of Zend_Db_Table_Abstract
as a "table" and Zend_Db_Table_Row_Abstract
as "row". Very rarely do I see direct calls to select objects, SQL, or the built in ZF database methods in my controllers. I try to hide the logic of requesting specific records to calls for behind Zend_Db_Table_Abstract
like so:
class Users extends Zend_Db_Table_Abstract {
protected $_name = 'users';
protected $_rowClass = 'User'; // <== THIS IS REALLY HELPFUL
public function getById($id) {
// RETURNS ONE INSTANCE OF 'User'
}
public function getActiveUsers() {
// RETURNS MULTIPLE 'User' OBJECTS
}
}
class User extends Zend_Db_Table_Row_Abstract {
public function setPassword() {
// SET THE PASSWORD FOR A SINGLE ROW
}
}
/* CONTROLLER */
public function setPasswordAction() {
/* GET YOUR PARAMS */
$users = new Users();
$user = $users->getById($id);
$user->setPassword($password);
$user->save();
}
有很多方法可以解決這個問題.不要認為這是唯一的,但我嘗試遵循 ZF 的設(shè)計意圖.(這里有更多我的關(guān)于這個主題的想法和鏈接.)這種方法確實有點類很重,但我覺得它讓控制器專注于處理輸入和與視圖協(xié)調(diào);讓模型去做特定于應用程序的工作.
There are numerous ways to approach this. Don't think this is the only one, but I try to follow the intent of the ZF's design. (Here are more of my thoughts and links on the subject.) This approach does get a little class heavy, but I feel it keeps the controllers focused on handling input and coordinating with the view; leaving the model to do the application specific work.
這篇關(guān)于Zend 框架中的模型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!