我正在構建一個Zend Framework應用程序,其中Model層被分離爲服務和模型。控制器動作調用服務方法,然後調用模型方法。在Zend_Registry中存儲數據vs類屬性
例如:語言控制器:: addAction()檢查表單是否被提交併且有效。如果是這樣,它將表單數據傳遞給Service_Language :: add(),在調用Model_Language :: add()之前將一些業務邏輯應用於數據,這有效地將記錄添加到數據庫。
這意味着大多數控制器操作都需要一個服務類的實例,並且服務類中的大多數方法都需要一個模型類的實例。
我用來做什麼的這樣的(一個服務類的例子)
class Service_Language
{
public function add()
{
$languageModel = new Model_Language;
// perform some business logic and add record
}
public function edit()
{
$languageModel = new Model_Language;
// perform some business logic and edit record
}
public function delete()
{
$languageModel = new Model_Language;
// perform some business logic and delete record
}
}
它不僅成爲累贅,在更復雜的應用中,控制器的操作調用多個服務方法,有將是多相同模型類的實例,這是不必要的。
一位同事告訴我要考慮兩個選項:
- 保持模型的實例在服務的屬性
- 保持模型實例合適的詞彙
我認爲最好的辦法將是第一個選擇。原因是Zend_Registry充當全球容器。我們不希望我們的Model實例在我們的Controller操作中可用,這是糟糕的體系結構。你對此有何看法?
第一個選項可以實現如下:
class Service_Language
{
protected $_model = null;
function setModel()
{
$this->_model = new Model_Language();
}
function getModel()
{
if($this->_model == null)
{
$this->setModel();
}
return $this->_model;
}
public function add()
{
$languageModel = $this->getModel();
// perform some business logic and add
}
}
也許更適合http://programmers.stackexchange.com/ – Phil