1 | <?php namespace Darryldecode\Cart; |
||
13 | class ItemCollection extends Collection |
||
14 | { |
||
15 | |||
16 | /** |
||
17 | * Sets the config parameters. |
||
18 | * |
||
19 | * @var |
||
20 | */ |
||
21 | protected $config; |
||
22 | |||
23 | /** |
||
24 | * ItemCollection constructor. |
||
25 | * @param array|mixed $items |
||
26 | * @param $config |
||
27 | */ |
||
28 | public function __construct($items, $config = []) |
||
34 | |||
35 | /** |
||
36 | * get the sum of price |
||
37 | * |
||
38 | * @return mixed|null |
||
39 | */ |
||
40 | public function getPriceSum() |
||
44 | |||
45 | public function __get($name) |
||
46 | { |
||
47 | if ($this->has($name) || $name == 'model') { |
||
48 | return !is_null($this->get($name)) ? $this->get($name) : $this->getAssociatedModel(); |
||
|
|||
49 | } |
||
50 | return null; |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * return the associated model of an item |
||
55 | * |
||
56 | * @return bool |
||
57 | */ |
||
58 | protected function getAssociatedModel() |
||
68 | |||
69 | /** |
||
70 | * check if item has conditions |
||
71 | * |
||
72 | * @return bool |
||
73 | */ |
||
74 | public function hasConditions() |
||
85 | |||
86 | /** |
||
87 | * check if item has conditions |
||
88 | * |
||
89 | * @return mixed|null |
||
90 | */ |
||
91 | public function getConditions() |
||
96 | |||
97 | /** |
||
98 | * get the single price in which conditions are already applied |
||
99 | * @param bool $formatted |
||
100 | * @return mixed|null |
||
101 | */ |
||
102 | public function getPriceWithConditions($formatted = true) |
||
123 | |||
124 | /** |
||
125 | * get the sum of price in which conditions are already applied |
||
126 | * @param bool $formatted |
||
127 | * @return mixed|null |
||
128 | */ |
||
129 | public function getPriceSumWithConditions($formatted = true) |
||
133 | } |
||
134 |
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_function
expects aPost
object, and outputs the author of the post. The base classPost
returns a simple string and outputting a simple string will work just fine. However, the child classBlogPost
which is a sub-type ofPost
instead decided to return anobject
, and is therefore violating the SOLID principles. If aBlogPost
were passed tomy_function
, PHP would not complain, but ultimately fail when executing thestrtoupper
call in its body.