Kohana-在控制器之间传递ORM对象的最佳方法?
我有一个扩展ORM的Model_组 我有一个控制器组,它得到一个新的ORM:Kohana-在控制器之间传递ORM对象的最佳方法?,orm,controller,kohana-3,hmvc,kohana-orm,Orm,Controller,Kohana 3,Hmvc,Kohana Orm,我有一个扩展ORM的Model_组 我有一个控制器组,它得到一个新的ORM: public function before() { global $orm_group; $orm_group = ORM::factory('Group'); } …它有各种方法可以使用它来获取不同的数据子集,例如 public function action_get_by_type() { global $orm_group; $type = $this->request-
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();
}
然后我有另一个控制器(在一个单独的模块中),我想用它来操作对象并调用相关的视图。让我们称之为控制器页面
$orm_object = // Get the $result from Controller_Group somehow!
$this->template->content = View::factory( 'page1' )
->set('orm_object', $orm_object)
将ORM对象从Controller_组传递到Controller_页面的最佳方式是什么?这是个好主意吗?如果没有,为什么没有,还有什么更好的方法
将它们分离到不同控制器中的原因是,我希望能够从其他模块中重用Controller_组中的方法。每个模块可能希望以不同的方式处理对象。这是我将采用的方式,但首先我想指出,在此上下文中,您不应使用
全局
如果您想在before
函数中设置ORM模型,只需在控制器中创建一个变量并按如下方式添加它
public function before()
{
$this->orm_group = ORM::factory('type');
}
在型号中
还应添加访问数据的功能,并使控制器尽可能小。你的模型可能看起来像这样
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);
}
在你的控制器中,你可以做这样的事情
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);
}
我希望这能有所帮助。我总是为这样的东西创建一个helper类
Class Grouphelper{
public static function getGroupByType($type){
return ORM::factory('Group')->where('type','=',$type)->find_all();
}
}
现在,您可以根据需要按类型获取组:
Grouphelper::getGroupByType($type);
我认为函数
action\u get\u by\u type
应该是ORM模型中的一个函数。然后你可以在你想要的每个控制器中调用这个函数。这是一个有趣的尝试。那么你的意思是我会通过执行$result=$orm\u group->get\u by\u type($type)来调用它吗代码>?非常感谢!还感谢您提供了关于使用全局变量的指针,我不知道为什么要这样做——只是尝试了不同的事情!这也是一个有效和有用的答案,谢谢。我现在需要考虑在我正在构建的应用程序的上下文中,哪个选项最适合我。