축약 함수
1public function instance($instance = null)2{3 $instance = $instance ?: self::DEFAULT_INSTANCE;4 $this->instance = sprintf('%s.%s', 'cart', $instance);5 return $this;6}
배열인지 확인하기
1if ($this->isMulti($id)) { 2 return array_map(function ($item) { 3 return $this->add($item); 4 }, $id); 5} 6 7array_map( 함수(배열값), 배열); 8 9/**10* Check if the item is a multidimensional array or an array of Buyables.11*12* @param mixed $item13* @return bool14*/15private function isMulti($item)16{17 if (!is_array($item)) return false;18 return is_array(head($item)) || head($item) instanceof Buyable;19}20 21is_array()22head() 이 함수는 뭐지?
세션 확인하기
1protected function getContent() 2{ 3 $content = $this->session->has($this->instance) 4 ? $this->session->get($this->instance) 5 : new Collection; 6 return $content; 7} 8 9session->has();10session->get();
1public function get($rowId)2{3 $content = $this->getContent();4 if (!$content->has($rowId))5 throw new InvalidRowIDException("The cart does not contain rowId {$rowId}.");6 return $content->get($rowId);7}
Class 자신이 갖고 있는 static 함수를 이용해서 직접 생성하는 방벙
1 2 public function __construct($id, $name, $price, array $options = []) 3 { 4 if(empty($id)) { 5 throw new \InvalidArgumentException('Please supply a valid identifier.'); 6 } 7 if(empty($name)) { 8 throw new \InvalidArgumentException('Please supply a valid name.'); 9 }10 if(strlen($price) < 0 || ! is_numeric($price)) {11 throw new \InvalidArgumentException('Please supply a valid price.');12 }13 $this->id = $id;14 $this->name = $name;15 $this->price = floatval($price);16 $this->options = new CartItemOptions($options);17 $this->rowId = $this->generateRowId($id, $options);18 }19 20 /**21 * Create a new instance from the given array.22 *23 * @param array $attributes24 * @return \App\CartItem25 */26 use Illuminate\Support\Arr;27 28 public static function fromArray(array $attributes)29 {30 $options = Arr::get($attributes, 'options', []);31 return new self($attributes['id'], $attributes['name'], $attributes['price'], $options);32 }33 34/**35 * Create a new instance from the given attributes.36 *37 * @param int|string $id38 * @param string $name39 * @param float $price40 * @param array $options41 * @return \App\CartItem42 */43public static function fromAttributes($id, $name, $price, array $options = [])44{45 return new self($id, $name, $price, $options);46}
Generate a unique id for the cart item.
1protected function generateRowId($id, array $options)2{3 ksort($options);4 return md5($id . serialize($options));5}
배열 클래스 만들기
1namespace App; 2 3use Illuminate\Support\Collection; 4 5class CartItemOptions extends Collection 6{ 7 /** 8 * Get the option by the given key. 9 *10 * @param string $key11 * @return mixed12 */13 public function __get($key)14 {15 return $this->get($key);16 }17}
1
1
1
1
1
1
1