author:咔咔
wechat:fangkangfk
咱們在作登錄以前,在這裏提出一個知識點,那就是三層架構。php
三層架構分別爲controller,server,model
controller:控制層,接收用戶請求,並對用戶的請求作出相應。同時會調用server完成項目的功能程序員
service:業務邏輯層,完成項目中的某個功能,它會調用modle層的方法來操做數據庫數據庫
model:模型層,此模型非tp框架中的模型,這個模型只會有一件事那就是數據庫的CURD操做json
下來咱們對登陸代碼進行優化:架構
從入行到寫博客的今天這份登陸頁面的代碼貌似一直是這個樣子,如今咱們進行優化app
這段代碼的耦合程度是不高的,但做爲一個極力追求極致的程序員來講仍是有問題的,這就是爲何在一開始我介紹了三層架構的概念框架
controller就是處理用戶請求和對用戶請求作出相應,並調用對應的service來完成項目功能fetch
可是這段代碼咱們就能夠看到邏輯層代碼也就是service層的代碼跟controller層代碼耦合了優化
下來咱們開始優化這層代碼this
1.咱們須要建立本身的service
這是自定義命令行建立service的方法
https://blog.csdn.net/fangkang7/article/details/83415607
將login的邏輯層代碼拿過來
/* author:咔咔 wechat:fangkangfk */ <?php namespace app\service; use app\model\User; class UserService { public function login($username,$password) { $user = User::where(['user_name'=>$username])->find(); if(!$user){ //用戶名不存在 return ['code'=>false,'msg'=>'用戶名不存在']; } if($user->user_status != 1){ // 用戶是否被封 return ['code'=>false,'msg'=>'帳號被封']; } if(!password_verify($password,$user->user_password)){ // 密碼錯誤,登陸失敗 return ['code'=>false,'msg'=>'密碼錯誤']; } //登陸成功 return ['code'=>false,'msg'=>'登陸成功']; } }
修改login的代碼
<?php namespace app\admin\controller; use think\Controller; use app\model\user\User; use app\service\UserService; use Request; use Db,Log; class Login extends Controller { private $userService; /** * 初始化 */ public function initialize() { $this->userService = new UserService; } /** * 登陸 * @return \think\Response */ public function login() { if(Request::isPost()){ $username = Request::param('username'); $password = Request::param('password'); return json($this->suerServcie->login($username,$password)); } return $this->fetch(); } }