Take the price of a commodity as an example: if the user is logged in and is VIP, get VIP price, otherwise the normal price;
Before processing:
Public functionGetPrice () {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))//if it is VIP, get preferential price returnSelf::Getvipprice (); } returnSelf::Getnormalprice (); }
After processing:
Public functionGetPrice () {if(Self::ISVIP ())returnSelf::Getpartnerprice (); returnSelf::Getnormalprice (); } Public functionIsvip () {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;
Of course,Getnormalprice and Getpartnerprice also use the same treatment ;
In this way, the code is not only easy to read, but also easier to reuse;
PS: This is very simple, but seldom used before, because it is not necessary to reuse, in fact, the main purpose of the code is easy to read, reuse is the second
Extract Method-Extraction methods