【发布时间】:2011-06-27 22:07:10
【问题描述】:
我正在开发一个基于 PHP 的 Model-View-Controller 结构化网站。我知道模型应该处理业务逻辑,视图向用户呈现 HTML(或其他),并且控制器促进了这一点。我遇到困难的地方是表格。 我在控制器中放了多少处理,我的模型放了多少?
假设我正在尝试更新用户的名字和姓氏。我想要做的是使用 AJAX 向我的一个控制器提交一个表单。我希望(再次)在服务器端验证数据,如果有效,将其保存到数据库中,然后将 JSON 响应返回给视图,作为成功或错误。
我应该在控制器中创建用户模型的实例,还是应该让控制器中继到模型中的静态方法?这是如何工作的两个示例:
选项 #1:在模型中处理 POST
<form action="/user/edit-user-form-submit/" method="post">
<input type="text" name="firstname">
<input type="text" name="lastname">
<button type="submit">Save</button>
</form>
<?php
class user
{
public function __construct($id){} // load user from database
public function set_firstname(){} // validate and set first name
public function set_lastname(){} // validate and set last name
public function save_to_database(){} // save object fields to database
public static function save_data_from_post()
{
// Load the user
$user = new user($_POST['id']);
// Was the record found in the db?
if($user->exists)
{
// Try to set these fields
if(
$user->set_firstname($_POST['firstname'])
and
$user->set_lastname($_POST['lastname'])
)
{
// No errors, save to the dabase
$user->save_to_database();
// Return success to view
echo json_encode(array('success' => true));
}
else
{
// Error, data not valid!
echo json_encode(array('success' => false));
}
}
else
{
// Error, user not found!
echo json_encode(array('success' => false));
}
}
}
class user_controller extends controller
{
public function edit_user_form()
{
$view = new view('edit_user_form.php');
}
public function edit_user_form_submit()
{
user::save_data_from_post();
}
}
?>
选项 #1:在模型中处理 POST
<form action="/user/edit-user-form-submit/" method="post">
<input type="text" name="firstname">
<input type="text" name="lastname">
<button type="submit">Save</button>
</form>
<?php
class user
{
public function __construct($id){} // load user from database
public function set_firstname(){} // validate and set first name
public function set_lastname(){} // validate and set last name
public function save_to_database(){} // save object fields to database
}
class user_controller extends controller
{
public function edit_user_form()
{
$view = new view('edit_user_form.php');
}
public function edit_user_form_submit()
{
// Load the user
$user = new user($_POST['id']);
// Was the record found in the db?
if($user->exists)
{
// Try to set these fields
if(
$user->set_firstname($_POST['firstname'])
and
$user->set_lastname($_POST['lastname'])
)
{
// No errors, save to the dabase
$user->save_to_database();
// Return success to view
echo json_encode(array('success' => true));
}
else
{
// Error, data not valid!
echo json_encode(array('success' => false));
}
}
else
{
// Error, user not found!
echo json_encode(array('success' => false));
}
}
}
?>
这两个例子做的事情完全相同,我意识到这一点。但是这样做有正确和错误的方法吗?我读过很多关于瘦控制器和胖模型的文章,选项#1 来自哪里。你是怎么处理的?谢谢,很抱歉这个问题太长了!
【问题讨论】:
标签: php model-view-controller validation forms