CakePHP如何将错误数据从模型传回控制器


CakePHP how to pass error data from the Model back to Controller

在一些特殊情况下,只是记录一个错误是不够的,我想传递一个错误数组或自定义错误字符串从一个模型到调用控制器,以便在电子邮件中发送该数据给我。

我想只是从模型本身发送电子邮件,但我在某处读到它激怒了MVC最佳实践之神。我看了看CakePHP API,没有找到任何看起来像我需要的东西,所以我在这里问,看看我是否错过了什么。

编辑:我在beforeSave()方法中做了一些特殊的处理。

谢谢!杰森

哈哈,在CakePHP 2.0中,Email类将成为一等公民,而不是组件。

因此,我不会担心从模型或shell或其他有用的地方发送电子邮件会激怒MVC之神。

你必须跳过一些环节:

// 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();