1 | <?php |
||
15 | class LazyLoadCollection implements CollectionInterface |
||
16 | { |
||
17 | use CollectionTrait { |
||
18 | CollectionTrait::items as private itemsInternal; |
||
19 | } |
||
20 | |||
21 | private $initialized = false; |
||
22 | private $initializer; |
||
23 | |||
24 | /** |
||
25 | * Constructor. |
||
26 | * |
||
27 | * Callback passed to $initializer argument |
||
28 | * will be executed when accessing collection items first time. |
||
29 | * |
||
30 | * @param callable $initializer callable that returns collection items |
||
31 | */ |
||
32 | 9 | public function __construct(callable $initializer) |
|
36 | |||
37 | 9 | protected function &items() |
|
38 | { |
||
39 | 9 | if (!$this->initialized) { |
|
40 | 9 | $data = &$this->itemsInternal(); |
|
41 | 9 | $data = call_user_func($this->initializer); |
|
42 | 9 | $this->initialized = true; |
|
43 | 9 | } |
|
44 | |||
45 | 9 | return $this->itemsInternal(); |
|
46 | } |
||
47 | |||
48 | /** |
||
49 | * Creates collection of items. |
||
50 | * |
||
51 | * Override it if you need to implement |
||
52 | * derived collection that requires specific initialization. |
||
53 | * |
||
54 | * @param array $items |
||
55 | * |
||
56 | * @return static |
||
57 | */ |
||
58 | 1 | protected function createCollection(array $items) |
|
62 | } |
||
63 |