2012-11-13 21 views
2

我正在構建一個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 
    } 
} 
+0

也許更適合http://programmers.stackexchange.com/ – Phil

回答

0

你的說明,這聽起來像你的服務類需要緊密耦合模型。

在這種情況下,我認爲不需要爲您的模型公開一個公共getter/setter - 在實際情況下您是否需要爲該服務設置另一個模型?

在這種情況下,將模型分配給屬性很有意義 - 爲什麼不在構造函數中執行此操作?

class Service_Language 
{ 
    protected $_model = null; 

    public function __construct() 
    { 
     $this->_model = new Model_Language(); 
    } 

    public function add() 
    { 
     // perform some business logic and add 
     $this->_model->add($data); 
    } 

    public function edit() 
    { 
     // perform some business logic and add 
     $this->_model->edit($data); 
    } 
} 
+0

服務層是執行業務邏輯,而不是在它的每一個方法都需要訪問模型實例。我想出了一個解決方案,你會發現下面... –

0

構造將是一個不錯的選擇,而不是在服務層的每一個方法都需要有一個模型實例來完成其工作,所以我最後只是這樣。我對OOP編程比較陌生,所以我想知道這是否是一個好的解決方案。任何想法都是值得歡迎的。

class Service_Language 
{ 

    protected $_model = null; 

    protected function setModel() 
    { 
     $this->_model = new Model_Language(); 
    } 

    protected function getModel() 
    { 
     if($this->_model == null) 
     { 
      $this->setModel(); 
     } 

     return $this->_model; 
    } 

    // Function where model is needed 
    public function add($data) 
    { 
     // Perform some business logic 

     $this->getModel()->add($data); 

     // return something 
    } 

    // Function where no model is needed 
    public function add($data) 
    { 
     // Perform some business logic 

     // return something 
    } 
}  
相關問題