User.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. /**
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fecshop\yii\web;
  10. use Yii;
  11. /**
  12. * @author Terry Zhao <2358269014@qq.com>
  13. * @since 1.0
  14. */
  15. class User extends \yii\web\User
  16. {
  17. /**
  18. * 重写该方法的作用为:当用户登录账户设置为cookie的时候
  19. * 购物车信息,通过cookie获取的用户id,在session中设置cart_id.
  20. */
  21. protected function loginByCookie()
  22. {
  23. $data = $this->getIdentityAndDurationFromCookie();
  24. if (isset($data['identity'], $data['duration'])) {
  25. $identity = $data['identity'];
  26. $duration = $data['duration'];
  27. if ($this->beforeLogin($identity, true, $duration)) {
  28. $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
  29. $id = $identity->getId();
  30. $ip = Yii::$app->getRequest()->getUserIP();
  31. Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
  32. $this->afterLogin($identity, true, $duration);
  33. /**
  34. * 如果user组件配置enableAutoLogin = true
  35. * 当session失效后,就会调用当前方法,cookie获取信息后,重新使用session登录
  36. * 因此,在账号重新恢复登录状态后,当前账户的购物车也要恢复。
  37. * 下面的代码就是在cookie恢复登录状态后,通过当前账户的id,搜索出来购物车信息
  38. * 然后把对应的购物车的cart_id,保存到cookie中。
  39. */
  40. $customer_cart = Yii::$service->cart->quote->getCartByCustomerId($id);
  41. $cart_id = isset($customer_cart['cart_id']) ? $customer_cart['cart_id'] : '';
  42. //echo $cart_id;
  43. if ($cart_id) {
  44. Yii::$service->cart->quote->setCartId($cart_id);
  45. }
  46. //Yii::$service->cart->mergeCartAfterUserLogin();
  47. }
  48. }
  49. }
  50. }