2013-10-30 19 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

相关问题