可以說我有發送電子郵件的一個基本的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。 –