可以说我有发送电子邮件的一个基本的HTML表单:PHP MVC脂肪控制器VS高脂模型
<form action="contactSubmit" method="POST">
<label for="name" class="italic">Name:</label>
<input type="text" name="name" value="" maxlength="20" required="required" autofocus="autofocus" />
<label for="email" class="italic">E-mail:</label>
<input type="email" name="reply_to" value="" maxlength="255" required="required" />
<label for="comments" class="italic">Comments:</label>
<textarea name="message" rows="10" cols="50" required="required"></textarea>
<br />
<input type="submit" class="submit" value="Send" />
</form>
目前所有的验证是在控制器完成:
// submit contact request
public function contactSubmit() {
// process form if submitted
if ($this->formSubmit()) {
// validate input
$name = isset($_POST['name']) && $this->validate($_POST['name'], null, 20) ? $_POST['name'] : null;
$reply_to = isset($_POST['reply_to']) && $this->validate($_POST['reply_to'], 'email', 255) ? $_POST['reply_to'] : null;
$message = isset($_POST['message']) && $this->validate($_POST['message']) ? $_POST['message'] : null;
// proceed if required fields were validated
if (isset($name, $reply_to, $message)) {
$to = WEBMASTER;
$from = '[email protected]' . $_SERVER['SERVER_NAME'];
$reply_to = $name . ' <' . $reply_to . '>';
$subject = $_SERVER['SERVER_NAME'] . ' - Contact Form';
// send message
$mail = $this->model->build('mail');
if ($mail->send($to, $from, $reply_to, $subject, $message)) {
$_SESSION['success'] = 'Your message was sent successfully.';
} else {
// preserve input
$_SESSION['preserve'] = $_POST;
// highlight errors
$_SESSION['failed'] = 'The mail() function failed.';
}
} else {
// preserve input
$_SESSION['preserve'] = $_POST;
// highlight errors
if (!isset($name)) {
$_SESSION['failed']['name'] = 'Please enter your name.';
}
if (!isset($reply_to)) {
$_SESSION['failed']['reply_to'] = 'Please enter a valid e-mail.';
}
if (!isset($message)) {
$_SESSION['failed']['message'] = 'Please enter your comments.';
}
}
}
$this->view->redirect('contact');
}
我想从“胖控制器”转向“胖控制器”,但是我不能为我的生活弄清楚如何将验证从前一个控制器完全移植到前面的模型中:
public function send($to, $from, $reply_to, $subject, $message) {
// generic headers
$headers = 'MIME-Version: 1.0' . PHP_EOL;
$headers .= 'From: ' . $from . PHP_EOL; // should belong to a domain on the server
$headers .= 'Reply-to: ' . $reply_to . PHP_EOL;
// send message
return mail($to, $subject, $message, $headers);
}
形式只有3个所需的字段,而模型的方法接受5.表单字段的描述是从输入的名称,这使得难以以自定义的错误消息,同时保持模型便携式用于其它应用使用不同。看起来,我所做的每一次尝试都变得非常胖,仍然没有达到与初始方法相同的灵活性。
可能有人请告诉我一个干净的方式从控制器移动验证的模型,同时仍保持自定义错误消息的灵活性,并保持模型的便携性在其他应用程序使用?
[MVC Validation Advice]的可能重复(http://stackoverflow.com/questions/19351502/mvc-validation-advice) –
验证的部分与业务逻辑相关,应在[域对象] (http://c2.com/cgi/wiki?DomainObject)。数据完整性检查应该通过存储抽象来处理。类似MVC体系结构中的控制器具有**没有任何**用于验证。此外,没有“胖模特”。模型不是一个类。 –
@tereško当他说模型(实体,数据对象,命令对象,你在域层中拥有的任何对象)时,他指的是域对象。但是没有任何mvc框架真正教会程序员如何构建域图层。例如,Laravel在文档中为模型层提供了一种数据驱动的方式,而不是DDD。 –