abstrakt:<?php/** * Created by PhpStorm. * User: Administrator * Date: 2018/7/23 * Time: 10:44 */namespace app\admin\controller;use app\admin\controller\Common;use app\admin\model\ProductModel;use app\admin
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/23
* Time: 10:44
*/
namespace app\admin\controller;
use app\admin\controller\Common;
use app\admin\model\ProductModel;
use app\admin\model\SortModel;
use think\facade\Request;
use think\facade\Session;
class Product extends Common
{
public function index()
{
// 實例化模型
$product = new ProductModel();
// 查詢數(shù)據(jù)并按照id進(jìn)行排序每頁八條數(shù)據(jù)
$products = $product->order('id', 'desc')->paginate(8);
// 將數(shù)據(jù)賦值給模板
$this->view->products = $products;
// 渲染產(chǎn)品列表
return $this->fetch();
}
public function add()
{
// 實例化并查詢分類
$sorts = SortModel::all();
// 將數(shù)據(jù)賦值到模板
$this->view->sorts = $sorts;
//渲染產(chǎn)品添加界面
return $this->fetch();
}
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 DoAdd()
{
// 獲取提交出來的數(shù)據(jù)
$data = Request::param();
// 將產(chǎn)品名獨立出來
$title = $data['title'];
// 利用產(chǎn)品名作為查詢條件查詢對應(yīng)的數(shù)據(jù)
$info = ProductModel::where('title', $title)->find();
// 判斷是否查詢到相同的產(chǎn)品名稱
if ($info == true) {
// 返回提示信息
return ['res' => 0, 'msg' => '產(chǎn)品標(biāo)題重復(fù)!'];
}
// 加入添加時間
$data['time'] = time();
// 添加發(fā)布管理員
$data['username'] = Session::get('username');
// 實例化模型
$product = new ProductModel();
// 進(jìn)行添加并驗證
if ($product->save($data)) {
// 返回提示信息
return ['res' => 1, 'msg' => '發(fā)布成功!'];
} else {
// 返回提示信息
return ['res' => 0, 'msg' => '發(fā)布失?。?#39;];
}
}
public function edit()
{
$proId = Request::param('id');
$product = ProductModel::get($proId);
$this->view->product = $product;
// 渲染產(chǎn)品修改界面
return $this->fetch();
}
public function DoEdit()
{
// 獲取提交過來的數(shù)據(jù)
$data = Request::param();
$product = new ProductModel();
$data['time'] = time();
$data['username'] = Session::get('username');
$info = $product->save([
'title' => $data['title'],
'desc' => $data['desc'],
'content' => $data['content'],
'once' => $data['once'],
'over_night' => $data['over_night'],
'time' => $data['time'],
'username' => $data['username'],
], ['id' => $data['id']]);
if ($info) {
return ['res' => 1, 'msg' => '更新成功!'];
} else {
return ['res' => 0, 'msg' => '更新失敗!'];
}
}
public function del()
{
// 獲取需要刪除的產(chǎn)品id
$proId = Request::param('id');
$product = new ProductModel();
if ($product->destroy($proId)) {
return ['res'=>1,'msg'=>'刪除成功!'];
}
}
}
Korrigierender Lehrer:天蓬老師Korrekturzeit:2019-04-12 15:44:39
Zusammenfassung des Lehrers:$product = new ProductModel(); 類方法中, 盡可能不要出現(xiàn)這樣的直接實例化的語句, 推薦使用依賴注入的方式,通過參數(shù)將外部對象注入到方法中