2013-10-30 20 views
0

我有擴展ORM的Model_Group。Kohana - 在控制器之間傳遞ORM對象的最佳方式?

我有Controller_Group是得到一個新的ORM:

public function before() 
{ 
    global $orm_group; 
    $orm_group = ORM::factory('Group'); 
} 

...它有一個用它來獲取數據的不同子集,如各種方法......

public function action_get_by_type() 
{ 
    global $orm_group; 
    $type = $this->request->param('type'); 
    $result = $orm_group->where('type', '=', $type)->find_all(); 
} 

然後我有另一個控制器(在一個單獨的模塊中),我想用它來操作對象並調用相關的視圖。我們稱之爲Controller_Pages。

$orm_object = // Get the $result from Controller_Group somehow! 
$this->template->content = View::factory('page1') 
    ->set('orm_object', $orm_object) 

什麼是將ORM對象從Controller_Group傳遞到Controller_Pages的最佳方法是什麼?這是一個好主意嗎?如果沒有,爲什麼不,以及有什麼更好的方法呢?

將它們分離到不同的控制器中的原因是因爲我希望能夠從其他模塊中重新使用Controller_Group中的方法。每個模塊可能都想以不同的方式處理對象。

+0

我覺得功能'action_get_by_type'應該是你的ORM模型中的一個函數。比你可以在每個你想要的控制器中調用該函數。 – Manuras

+0

這是一個有趣的事情。所以你的意思是我會通過執行'$ result = $ orm_group-> get_by_type($ type);''來調用它。 – SigmaSteve

回答

1

這是我會這樣做的方式,但首先我想指出,在這種情況下,您不應該使用global

如果您想在before函數中設置您的ORM模型,只需在控制器中創建一個變量並像這樣添加它即可。

public function before() 
{ 
    $this->orm_group = ORM::factory('type'); 
} 

在你Model您還應該添加訪問數據,並保持控制器儘可能小的功能。你的ORM模型可能看起來像這樣。

public class Model_Group extends ORM { 
    //All your other code 

    public function get_by_type($type) 
    { 
      return $this->where('type', '=', $type)->find_all(); 
    } 
} 

比你的控制器,你可以做這樣的事情。

public function action_index() 
{ 
    $type = $this->request->param('type'); 
    $result = $this->orm_group->get_by_type($type); 
} 

我希望這會有所幫助。

+0

**非常感謝!**也感謝您使用全局變量的指針,我不知道爲什麼我這麼做 - 只是嘗試不同的東西! – SigmaSteve

1

我總是創建一個輔助類的東西,這樣的

Class Grouphelper{ 
    public static function getGroupByType($type){ 
     return ORM::factory('Group')->where('type','=',$type)->find_all(); 
    } 
} 

現在你能得到你想要的組按類型:

Grouphelper::getGroupByType($type); 
+0

也是一個有效和有用的答案,謝謝。我現在需要考慮在我正在構建的應用程序的上下文中哪個選項最適合我。 – SigmaSteve

相關問題