tags:

views:

127

answers:

2

Is there any way in Kohana 3's ORM to run a chunk of code in a model, but only after that model has been loaded from the database? A simple example is a required has_one relationship.

   ORM::factory('user')->where('name', '=', 'Bob')->find();

Now what if all users have to have some other property, so if Bob doesn't exist, it will have to be created? Right now, in the place where this line is running, I'm checking for null primary key, and instructing the model to add that relationship if so. But is there any way to have it done by the model? The problem with the constructor is that models can be constructed empty just before being populated from the DB, as is visible in this example, so I don't want that.

+2  A: 

Try overloading the find() method in your Model:

class Model_User extends ORM {

    public function find($id = NULL) {
        $result = parent::find($id);
        if (!$result->loaded()) {
            // not found so do something
        }
        return $result;
    }

}
Lukman
+2  A: 

Just create model method with all logic required:

public function get_user($username)
{
    $this->where('name', '=', $username)->find();
    if ( ! $this->_loaded)
    {
        // user not found
    }
    else
    {
        // user exists, do something else
    }
    // make it chainable to use something like this:
    //   echo ORM::factory('user')->get_user('Bob')->username;
    return $this;
}
biakaveron
extending find would work as well but this way would leave find alone for other things as well and keep it a bit easier upgrade if the params change on the find method.
joelpittet