????:<?php /** * Created by PhpStorm. * User: Jason * Date: 2019/4/26 * Time: 8:11 */ namespace app\admin\controller; us
<?php namespace app\admin\controller; use think\facade\Request; use think\facade\Session; use app\admin\model\NewsModel; use app\admin\controller\Common; class News extends Common { // 新聞列表 public function index() { // 獲取新聞列表 $news = NewsModel::order('id','desc')->paginate(8); // 模板賦值 $this->assign('news',$news); // 渲染模板 return $this->fetch(); } // 添加新聞頁面 public function add() { // 渲染模板 return $this->fetch(); } // 添加操作 public function DoAdd() { // 獲取表單信息 $data = Request::param(); $data['time'] = time(); $data['username'] = Session::get('username'); $title = $data['title']; // 檢測新聞標(biāo)題是否存在 $news = NewsModel::where('title',$title)->find(); if($news) { return ['code'=>0,'msg'=>'新聞標(biāo)題重復(fù)']; } // 寫入數(shù)據(jù)庫中 if(NewsModel::create($data)) { return ['code'=>1,'msg'=>'發(fā)布成功']; } // 發(fā)布失敗 return ['code'=>0,'msg'=>'發(fā)布失敗']; } // 文件上傳 public function upload() { // 獲取上傳的圖片信息 $file = Request::file('img'); // 將文件上傳移動到指定目錄 if($info = $file->validate(['ext'=>'jpg,jpeg,png,gif'])->move('upload')) { // 返回上傳成功的信息 return json(['errno'=>0,'data'=>['/upload/'.$info->getSaveName()]]); } else { // 返回錯誤的信息 return $file->getError(); } } // 編輯頁面 public function edit() { // 獲取新聞ID $newId = Request::param('id'); // 根據(jù)新聞ID查找對應(yīng)的內(nèi)容數(shù)據(jù) $news = NewsModel::get($newId); // 個模板賦值 $this->assign('news',$news); // 渲染編輯頁面 return $this->fetch(); } // 修改編輯 public function DoEdit() { // 獲取上傳的數(shù)據(jù) $data = Request::param(); // 更新條件 $newId = $data['id']; // 更新數(shù)據(jù) $res = NewsModel::where('id',$newId)->update([ 'title'=>$data['title'], 'desc' =>$data['desc'], 'content'=>$data['content'], 'username'=>Session::get('username'), 'time'=>time(), ]); if($res) { // 返回更新成功 return ['code'=>1,'msg'=>'數(shù)據(jù)更新成功']; } // 返回更新失敗 return ['code'=>0,'msg'=>'數(shù)據(jù)更新失敗']; } // 刪除操作 public function DoDel() { $newId = Request::param('id'); // 刪除數(shù)據(jù) 使用軟刪除 $res = NewsModel::destroy($newId); if($res) { return ['code'=>1,'msg'=>'數(shù)據(jù)刪除成功']; } return ['code'=>0,'msg'=>'數(shù)據(jù)刪除失敗']; } }
?? ???:天蓬老師?? ??:2019-04-26 13:36:43
???? ??:框架的代碼,比較規(guī)范, 不錯, 就是方法的頭部注釋加上會更好