假设我有一个用于发送电子邮件的基本 HTML 表单:
<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 = 'nobody@' . $_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 个。表单字段的描述与输入名称不同,这使得难以自定义错误消息,同时保持模型在其他应用程序中的可移植性。似乎我所做的每一次尝试最终都变得可笑地肥胖,并且仍然没有达到与最初方法相同的灵活性。
有人可以向我展示一种将验证从控制器转移到模型的干净方法,同时仍然保持自定义错误消息的灵活性并保持模型在其他应用程序中使用的可移植性?