0

我有扩展 ORM 的 Model_Group。

我有获得新 ORM 的 Controller_Group:

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

4

2 回答 2

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);
}

我希望这有帮助。

于 2013-10-31T10:03:59.450 回答
1

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

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

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

Grouphelper::getGroupByType($type);
于 2013-10-31T11:07:04.713 回答