MODEL:
class MyCookie { //存储cookie public function checkCookie($data,$arr) { if (!empty($data)) { //重建数组 不能超过10 if ($count = sizeof($data) > 10) { array_splice($data, 11, $count); } //判断商品已经存在 foreach ($data as $k => $v) { if ($arr['commod_id'] == $v['commod_id']) { array_splice($data, $k, $k + 1); //删除重复元素 break; } } array_unshift($data, $arr); //将刚浏览的添加到数组开头 return $data; }else{ return $arr; } } }
Controller:
use App\Http\Controllers\Controller; use App\Http\Model\CommodInfo; use App\Http\Model\Controll; use App\Http\Model\MyCookie; use Illuminate\Http\Request; use Illuminate\Http\Response; use App\Http\Requests; use Illuminate\Support\Facades\Cookie; class CookieController extends Controller { //处理cookie数据 后浏览靠前 不重复 限制十条 public function setCookie(Request $request) { $id = $request->input("commod_id"); $arr1 = $request->cookie('name'); $arr2 = (new CommodInfo())->getGoodsCookie($id)->toArray(); if (empty($arr1)) $data[0] = $arr2; else $data = (new MyCookie())->checkCookie($arr1, $arr2); Cookie::queue('name', $data, 60 * 24 * 7); } public function getCookie(Request $request) { $value = $request->cookie('name'); return $value; } }
使用:
//获取商品详情和小图片 public function getGoodsDetail(Request $request) { if (!is_numeric($request->input("commod_id"))) { return redirect('/error'); } (new CookieController())->setCookie($request); if ($arr = (new CommodInfo())->getGoodsDetail($request->input("commod_id"))) { $arrImg = (new CommodImages())->getImages($arr->commod_id); return view('anhshop.index.goods_detail', compact('arr', 'arrImg')); } }
//获取
调用model的getCookie()