Cart.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace app\api\controller;
  3. use app\api\model\Cart as CartModel;
  4. use app\api\service\order\Checkout as CheckoutModel;
  5. /**
  6. * 购物车管理
  7. * Class Cart
  8. * @package app\api\controller
  9. */
  10. class Cart extends Controller
  11. {
  12. /* @var \app\api\model\User $user */
  13. private $user;
  14. /* @var \app\api\model\Cart $model */
  15. private $model;
  16. /**
  17. * 构造方法
  18. * @throws \app\common\exception\BaseException
  19. * @throws \think\exception\DbException
  20. */
  21. public function _initialize()
  22. {
  23. parent::_initialize();
  24. $this->user = $this->getUser();
  25. $this->model = new CartModel($this->user);
  26. }
  27. /**
  28. * 购物车列表
  29. * @return array
  30. * @throws \think\Exception
  31. * @throws \think\db\exception\DataNotFoundException
  32. * @throws \think\db\exception\ModelNotFoundException
  33. * @throws \think\exception\DbException
  34. */
  35. public function lists()
  36. {
  37. // 请求参数
  38. $param = $this->request->param();
  39. $cartIds = isset($param['cart_ids']) ? $param['cart_ids'] : '';
  40. // 购物车商品列表
  41. $goodsList = $this->model->getList($cartIds);
  42. // 获取订单结算信息
  43. $Checkout = new CheckoutModel;
  44. $orderInfo = $Checkout->onCheckout($this->user, $goodsList);
  45. return $this->renderSuccess($orderInfo);
  46. }
  47. /**
  48. * 加入购物车
  49. * @param int $goods_id 商品id
  50. * @param int $goods_num 商品数量
  51. * @param string $goods_sku_id 商品sku索引
  52. * @return array
  53. * @throws \app\common\exception\BaseException
  54. * @throws \think\exception\DbException
  55. */
  56. public function add($goods_id, $goods_num, $goods_sku_id)
  57. {
  58. if (!$this->model->add($goods_id, $goods_num, $goods_sku_id)) {
  59. return $this->renderError($this->model->getError() ?: '加入购物车失败');
  60. }
  61. // 购物车商品总数量
  62. $totalNum = $this->model->getTotalNum();
  63. return $this->renderSuccess(['cart_total_num' => $totalNum], '加入购物车成功');
  64. }
  65. /**
  66. * 减少购物车商品数量
  67. * @param $goods_id
  68. * @param $goods_sku_id
  69. * @return array
  70. */
  71. public function sub($goods_id, $goods_sku_id)
  72. {
  73. $this->model->sub($goods_id, $goods_sku_id);
  74. return $this->renderSuccess();
  75. }
  76. /**
  77. * 删除购物车中指定商品
  78. * @param $goods_sku_id (支持字符串ID集)
  79. * @return array
  80. */
  81. public function delete($goods_sku_id)
  82. {
  83. $this->model->delete($goods_sku_id);
  84. return $this->renderSuccess();
  85. }
  86. }