Question

I am thinking of overriding the save/create/update methods of ORM classes in an application being developed using Kohana PHP framework.

I would like to know whether it is a good practice to do so and what would be the pros and cons. My reason for doing this is to take all the duplicate code out of controller and put it in one place inside the overridden methods in model.

For eg. Consider a simple polls app. with two ORM classes - Model_Poll and Model_Choice with a one to many relationship.

right now, the following code would be placed in the controller for creating a new poll and also to save choices for it if found in $_POST

$poll = ORM::factory('poll');
$poll->name = 'some question ?';
$poll->save();
if ($this->request->post('choices')) {
   foreach ($this->request->post('choices') as $choice) {
       $c = ORM::factory('choice'); 
       $c->name = $choice;
       $poll->add($c);
   }       
}

I want to change this to following

in controller,

$poll = ORM::factory('poll');
$poll->name = 'some question ?';
$poll->set_choices($this->request->post('choices'));
$poll->save();

in Model_Poll,

public function create(Validation $validation = null) {
    $return = parent::create($validation);
    if ($this->_choices) {
        foreach ($this->_choices as $choice) {
           $c = ORM::factory('choice'); 
           $c->name = $choice;
           $this->add($c);
        }
    }
    return $return;        
}

public function set_choices($choices) {
    $this->_choices = $choices;
}

This create method will get internally called by the save method. Later on, if there are more things to be done, i can do it here itself.

Thanks for any help.

Was it helpful?

Solution

Your choice objects will not be saved ($c->save() required), so $this->add($c) will not work too.

Why dont use something like this:

$poll->save();
$poll->set_choices($this->request->post('choices'));

Where set_choices() method will create (if required) choices and save relations for current poll.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top