codeigniter-base-model icon indicating copy to clipboard operation
codeigniter-base-model copied to clipboard

Observers not working

Open paulcanning opened this issue 9 years ago • 2 comments
trafficstars

I am trying to get a simple observer working, but to no avail.

I am using the following code (as shown in the documentation)

class Business_model extends MY_Model
{
    public $_table = 'business';
    public $before_get = array('timestamps');

    protected function timestamps($row)
    {
        $row['created_at'] = $row['updated_at'] = date('Y-m-d H:i:s');
    return $row;
    }
}

Checking the variables using a break point, shows that the object returned does not contain the created_at or updated_at data.

Do I need to enable the triggers somehow?

I am using CI3 btw.

paulcanning avatar Mar 15 '16 11:03 paulcanning

OK, it seems like before_get is the wrong observer to use in my case.

I want to get the data, then append it. It seems whatever I do in before_get is getting overwritten.

So what use is before_get if data is going to be overwritten?

Looks like after_get works for me, for now.

paulcanning avatar Mar 15 '16 11:03 paulcanning

I'm finding that the before_create observer isn't firing to hash the password on user create. I fire the users into the database like so:

$this->user_model->insert(array(
    'forename' => 'Jim',
    'surname' => 'Testing',
    'username' => 'j.testing1234',
    'password' => 'awesomepassword'
));

Then in my user_model.php I have the following:

user_model.php

class User_model extends MY_Model{

    protected $before_create = array('hash_password');
    protected $before_update = array('hash_password');
    protected $soft_delete = true;

    public function __construct(){
        parent::__construct();
        $this->soft_delete = true;
    }

    /**
     * Hash Password
     *
     * Creates a cryptographically secure password hash for users
     * 
     * @param  array $user The database row representing the user
     * @return array      The database row representing the user
     */
    protected function hash_password($user){
        if(array_key_exists('password', $user)){
            $user['password'] = password_hash($user['password'], PASSWORD_BCRYPT);
        }
        return $user;
    }

}

robertmain avatar May 23 '16 11:05 robertmain