Search code examples
ormcontrollerkohana-3hmvckohana-orm

Kohana - Best way to pass an ORM object between controllers?


I have Model_Group that extends ORM.

I have Controller_Group that gets a new ORM:

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

...and it has various methods that use it to get different subsets of data, such as...

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

Then I have another controller (in a separate module) that I want to use to manipulate the object and call the relevant view. Let's call it Controller_Pages.

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

What is the best way to pass the ORM object from Controller_Group to Controller_Pages? Is this a good idea? If not, why not, and what better way is there of doing it?

The reason for separating them out into different controllers is because I want to be able to re-use the methods in Controller_Group from other modules. Each module may want to deal with the object in a different way.


Solution

  • This is the way I would do it, but first I would like to note that you shouldn't use global in this context.

    If you want to set your ORM model in the before function, just make a variable in your controller and add it like this.

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

    In your Model your should also add the functions to access data and keep the controllers as small as possible. You ORM model could look something like this.

    public class Model_Group extends ORM {
         //All your other code
    
         public function get_by_type($type)
         {
              return $this->where('type', '=', $type)->find_all();
         }
    }
    

    Than in your controllers you can do something like this.

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

    I hope this helps.