2011-08-29 71 views
0

我想在使用Kohana PHP框架開發的應用程序中重寫ORM類的保存/創建/更新方法。關於覆蓋ORM保存方法的想法

我想知道這是否是一種好的做法,什麼是利弊。我這樣做的理由是將所有重複代碼從控制器中取出,並將其放在模型中重寫的方法內的一個地方。

例如,考慮一個簡單的民意調查應用程序。與兩個ORM類 - Model_Poll和Model_Choice具有一對多關係。

現在,下面的代碼將被放置在控制器如果發現在$ _ POST

$poll = ORM::factory('poll'); 
$poll->name = 'some question ?'; 
$poll->save(); 
if ($this->request->post('choices')) { 
    foreach ($this->request->post('choices') as $choice) { 
     $c = ORM::factory('choice'); 
     $c->name = $choice; 
     $poll->add($c); 
    }  
} 

我想改變這下面

創建一個新的投票,也保存了它的選擇

在控制器,

$poll = ORM::factory('poll'); 
$poll->name = 'some question ?'; 
$poll->set_choices($this->request->post('choices')); 
$poll->save(); 
在Model_Poll

public function create(Validation $validation = null) { 
    $return = parent::create($validation); 
    if ($this->_choices) { 
     foreach ($this->_choices as $choice) { 
      $c = ORM::factory('choice'); 
      $c->name = $choice; 
      $this->add($c); 
     } 
    } 
    return $return;   
} 

public function set_choices($choices) { 
    $this->_choices = $choices; 
} 

此創建方法將由save方法在內部調用。後來,如果還有更多事情要做,我可以在這裏做。

感謝您的任何幫助。

回答

1

您的選擇對象不會被保存(需要$c->save()),所以​​3210不會工作。

爲什麼不使用這樣的事情:

$poll->save(); 
$poll->set_choices($this->request->post('choices')); 

set_choices()方法將創建(如果需要)選擇和保存目前的投票關係。

+0

我忘了添加'$ c-> save()'部分。但我喜歡你的方法。感謝回覆。 – naiquevin