标签:
以获取一个商品的价格为例:如果用户已登录并且是vip,得到vip价,否则正常价;
处理前:
public function getPrice() { if (Auth::user()) { $userId = Auth::user()->UserID; $customerIds = $this->supplier->customers->map(function ($item) { return $item->format([‘customer_id‘]); })->toArray(); $customerIds = array_column($customerIds, ‘customer_id‘); if (in_array($userId, $customerIds))//如果是vip,获得优惠价 return self::getVIPPrice(); } return self::getNormalPrice(); }
处理后:
public function getPrice() { if (self::isVIP()) return self::getPartnerPrice(); return self::getNormalPrice(); } public function isVIP() { if (Auth::user()) { $userId = Auth::user()->UserID; $customerIds = $this->supplier->customers->map(function ($item) { return $item->format([‘customer_id‘]); })->toArray(); $customerIds = array_column($customerIds, ‘customer_id‘); if (in_array($userId, $customerIds)) return true; } return false;
当然,getNormalPrice 和 getPartnerPrice 也是使用了同样的处理;
通过这种手法,代码不仅变得易读,而且更容易复用;
ps:这种做法很简单,但以前很少用,因为觉得不需要复用;其实主要目的是代码易读,复用倒是其次
标签:
原文地址:http://www.cnblogs.com/xiaoyaxiaopingguo/p/5294564.html