摘要://新聞模塊 News.php<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019-02-18 * Time: 14:31 */ namespace&
//新聞模塊
News.php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019-02-18 * Time: 14:31 */ namespace app\admin\controller; use app\admin\controller\Common; use app\admin\model\NewsModel; use think\facade\Request; use think\facade\Session; class News extends Common { public function index() { $news= new NewsModel(); $new=$news->order('id','desc')->paginate(1); $this->view->new=$new; //渲染新聞列表 return $this->fetch(); } public function add() { //渲染添加界面 return $this->fetch(); } public function DoAdd() { //獲得數(shù)據(jù) $data=Request::param(); $data['time']=time(); $data['username']=Session::get('username'); //驗(yàn)證標(biāo)題是否重復(fù) $title=$data['title']; $news = NewsModel::where('title',"$title")->find(); //判斷是否重復(fù) if($news==true){ return ['res'=>0,'msg'=>'新聞標(biāo)題重復(fù)!']; } $new = new NewsModel(); if($new->save($data)){ return ['res'=>1,'msg'=>'發(fā)布成功!']; } else { return ['res'=>0,'msg'=>'發(fā)布失敗!']; } } public function upload() { // 獲取上傳的圖片信息 $file = Request::file('img'); // 驗(yàn)證圖片信息并移動(dòng)到指定目錄 if ($info = $file->validate(['ext' => 'jpg,jpeg,png,gif'])->move('upload')) { // 返回上傳成功信息 return json(['errno' => 0, 'data' => ['/upload/' . $info->getSaveName()]]); } else { // 返回錯(cuò)誤信息 return $file->getError(); } } public function edit() { //接受傳遞過來的id $newId = Request::param('id'); $new= NewsModel::get($newId); //將數(shù)據(jù)賦值到模板 $this->view->new=$new; //渲染界面 return $this->fetch(); } public function DoEdit() { //獲取提交的數(shù)據(jù) $data = Request::param(); //實(shí)例化模型 $new = new NewsModel(); //修改操作 $res = $new->save([ 'title'=>$data['title'], 'desc' =>$data['desc'], 'content'=>$data['content'], 'username'=>Session::get('username'), 'time'=>time(), ],['id'=>$data['id']]); if($res){ //返回修改成功信息 return ['res'=>1,'msg'=>'修改成功!']; }else{ return ['res'=>0,'msg'=>'修改失敗!']; } } public function del() { //獲取刪除的id $newId = Request::param('id'); //實(shí)例化new模型 $new = new NewsModel(); //刪除并驗(yàn)證 if($new->destroy($newId)){ //返回信息 return ['res'=>1,'msg'=>'刪除成功!']; }else{ //返回信息 return ['res'=>0,'msg'=>'刪除失敗!']; } } }
批改老師:韋小寶批改時(shí)間:2019-02-19 09:08:34
老師總結(jié):像使用框架來完成這種很簡(jiǎn)單的項(xiàng)目 基本上的增刪改查都很相似 只有一些業(yè)務(wù)邏輯上的不同而已 寫的很不錯(cuò) 繼續(xù)加油吧!