Search code examples
cakephpmodelcontrollerafter-save

cakephp how do you call a controller's action inside a model


I'm working within afterSave in my messages model. I'd like to send an email every time a message is created to notify the recepient of their new message. I have an action inside of the messages controller that sends the email and i'd like to call it from afterSave.

I've tried calling it like this:

function afterSave($created){
    if($created){
        $this->msgToEmail($this->data);
    }
}

i get a sql error because it looks for the function inside of the model instead of the controller.

How do i declare the model function? is it possible?


Solution

  • You use model methods inside other models, never ever a controller!

    So make your code a model method. then you can easily use it.

    In 1.3 You can hack the component in your model method for now. Until you can finally upgrade to 2.x.

    App::import('Component', 'Email');
    $this->Controller = new Controller();
    $this->Email = new EmailComponent(null);
    $this->Email->initialize($this->Controller);
    // from/to/subject/...
    $this->Controller->set('text', $this->data['Model']['content']);
    return $this->Email->send();