【问题标题】:Kohana - Best way to pass an ORM object between controllers?Kohana - 在控制器之间传递 ORM 对象的最佳方式?
【发布时间】:2013-10-30 13:23:52
【问题描述】:

我有扩展 ORM 的 Model_Group。

我的 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 中的方法。每个模块可能希望以不同的方式处理对象。

【问题讨论】:

  • 我认为函数 action_get_by_type 应该是你的 ORM 模型中的一个函数。你可以在你想要的每个控制器中调用该函数。
  • 这是一个有趣的观点。所以你的意思是我会通过 $result = $orm_group->get_by_type($type); 来调用它?

标签: orm controller kohana-3 hmvc kohana-orm


【解决方案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);
}

我希望这会有所帮助。

【讨论】:

  • 非常感谢! 也感谢您提供有关使用全局变量的指针,我不知道我为什么要这样做 - 只是尝试不同的东西!
【解决方案2】:

我总是为这样的东西创建一个帮助类

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

现在您可以根据需要按类型获取组:

Grouphelper::getGroupByType($type);

【讨论】:

  • 也是一个有效且有用的答案,谢谢。我现在需要考虑在我正在构建的应用程序的上下文中哪个选项最适合我。
猜你喜欢
  • 1970-01-01
  • 2010-10-08
  • 1970-01-01
  • 2015-09-10
  • 2019-04-03
  • 2018-06-22
  • 2016-10-13
  • 1970-01-01
  • 2019-07-29
相关资源
最近更新 更多