这是一个 user.php Controller
public function verifyLogin() {
if (isset($_POST["email"])) {
$e = $this->input->post("email");
$p = $this->input->post("pass");
$this->form_validation->set_rules("email", "email", "required|valid_email|xss_clean");
$this->form_validation->set_rules("pass", "password", "required|xss_clean");
if ($this->form_validation->run()) {
$data = array(
'select' => '*',
'table' => 'users',
'where' => "email = '$e' AND activated = '1'"
);
$checklogin = $this->query2->selectData($data);
if ($checklogin === FALSE) {
echo "quering userInfo fails. email is wrong or activation not done";
exit();
} else {
foreach ($checklogin as $row) {
$dbid = $row->id;
$dbusername = $row->username;
$dbpassword = $row->password;
$dbemail = $row->email;
if ($p === $dbpassword) {
$login_data = array(
'name' => $dbusername,
'email' => $dbemail,
'password' => $dbpassword,
'id' => $dbid,
'expire' => '86500',
'secure' => TRUE,
'logged_in' => TRUE
);
$this->input->set_cookie($login_data);
$this->session->set_userdata($login_data);
if ($this->session->userdata("logged_in")) {
$time = time();
$now = unix_to_human($time, TRUE, 'us');
$updateLogin = $this->query1->updateLogin($e, $now);
if ($updateLogin) {
echo "success";
} else {
echo 'update failed';
}
} else {
echo "session failed";
}
}else{
echo 'password incorrect';
}
}
}
} else {
echo "form validation fails";
}
} else {
$this->load->view('header');
$this->load->view('login');
$this->load->view('modal');
$this->load->view('footer');
}
}
这是 model.php
public function selectData($data){
if(isset($data['direction'])){
$dir = $data['direction'];
}else{
$dir = "ASC";
}
if(isset($data['offset'])){
$off = $data['offset'];
}else{
$off = '0';
}
if(isset($data['select']) && isset($data['table'])){
$this->db->select($data['select'])->from($data['table']);
}
if(isset($data['where'])){
$this->db->where($data['where']);
}
if(isset($data['order_by_name'])){
$this->db->order_by($data['order_by_name'], $dir);
}
if(isset($data['limit'])){
$this->db->limit($data['limit'], $off);
}
$query = $this->db->get();
if($query){
$d = $query->result();
return $d;
}else{
return FALSE;
}
}
这是查询数据库的好方法吗? 我是 MVC 新手,我到处都在阅读有关“胖模型和这个 Controller ”的内容 怎样才能使它成为一个好的mvc架构?
最佳答案
只有在开发时才可以从 Controller 中回显:
if ($checklogin === FALSE) {
echo "quering userInfo fails.
如果检查登录错误,则显示 View 或转到新方法,例如
if ($checklogin === FALSE) {
$this->showLoginFailed($errorMessage) ;
Controller 中的检查登录代码是可以重构为模型的一个很好的例子。那么如果您需要检查另一个 Controller 的登录,那就容易多了。将表单验证代码放入模型中是另一种选择。通常,当您验证表单代码时,您还会插入/更新数据库表 - 因此,将所有这些详细信息放在一个模型中可以使长期工作变得更容易。
“胖模型”并不意味着模型中的一种方法可以做一百件事。它意味着 Controller 说 - 该客户表单是否已验证并插入到数据库中?是还是不是? 3行代码。
该模型具有研究表单、验证、数据库等“丰富”细节的代码,与 Controller 中的 3 行相比,有 50 行或更多行。但模型中的方法仍然应该是干净的:小而具体。
关于mysql - Codeigniter 中的胖模型和瘦 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28661504/