CakePHP how to pass error data from the Model back to Controller
In some special cases where just logging an error isn't enough I would like to pass an error array or a custom error string from a Model to the calling Controller in order to send that data to me in 开发者_运维知识库an email.
I thought about just sending an email from the Model itself but I have read somewhere that it angers the MVC best practices gods. I looked around the CakePHP API and didn't find anything that looks like what I need so I'm asking here to see if I missed anything.
Edit: I'm doing some special processing in the beforeSave() method.
Thanks! Jason
Haha, going forward - in CakePHP 2.0 - the Email class will be a first-class citizen and not a component.
As such, I wouldn't worry about angering the MVC gods by sending email from (god-forbid) models or shells or other useful places.
You do have to jump through a few hoops though:
// we will need a controller, so lets make one:
App::import('Core', 'Controller');
$controller =& new Controller();
// lets grab the email component
App::import('Component', 'Email');
$email =& new EmailComponent();
// give it the reference to the controller
$email->initialize($controller);
// off we go...
$email->from = 'Name <noreply@example.com>';
$email->replyTo = 'noreply@example.com';
$email->sendAs = $format;
$email->to = $destination;
$email->subject = $subject;
// oh, this is why we needed the controller
$email->template = $template;
$controller->set(compact('items', 'subject'));
// done.
$sent = $email->send();
精彩评论