1 | <?php |
||
2 | declare(strict_types=1); |
||
3 | |||
4 | /** |
||
5 | * Decorator Implementation |
||
6 | * @category Ticaje |
||
7 | * @author Max Demian <[email protected]> |
||
8 | */ |
||
9 | |||
10 | namespace Ticaje\Contract\Traits; |
||
11 | |||
12 | /** |
||
13 | * Trait Singleton |
||
14 | * @package Ticaje\Contract\Traits |
||
15 | * This trait accomplishes singleton pattern to those classes that require to momentarily cache a result based on current execution thread. |
||
16 | */ |
||
17 | trait Singleton |
||
18 | { |
||
19 | /** |
||
20 | * @param $binder // The binder is a class property, preferably a protected/private one |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
![]() |
|||
21 | * @param callable $logic |
||
22 | * @return mixed |
||
23 | */ |
||
24 | protected function singleton($binder, callable $logic) |
||
25 | { |
||
26 | if (!$this->{$binder}) { |
||
27 | $this->{$binder} = $logic(); |
||
28 | } |
||
29 | return $this->{$binder}; |
||
30 | } |
||
31 | |||
32 | /** |
||
33 | * @param $binder |
||
34 | * @param callable $logic |
||
35 | * @param int $index |
||
36 | * @return mixed |
||
37 | */ |
||
38 | protected function singletonKeyed($binder, callable $logic, $index = 0) |
||
39 | { |
||
40 | if (!isset($this->{$binder}[$index])) { |
||
41 | $this->{$binder}[$index] = $logic(); |
||
42 | } |
||
43 | return $this->{$binder}[$index]; |
||
44 | } |
||
45 | } |
||
46 |