ContainerDoesNotExistException.php
6 years ago
ContainerFactory.php
6 years ago
IniConfigDefinitionSource.php
6 years ago
StaticContainer.php
6 years ago
StaticContainer.php
88 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Piwik - free/libre analytics platform |
| 4 | * |
| 5 | * @link https://matomo.org |
| 6 | * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later |
| 7 | */ |
| 8 | |
| 9 | namespace Piwik\Container; |
| 10 | |
| 11 | use DI\Container; |
| 12 | |
| 13 | /** |
| 14 | * This class provides a static access to the container. |
| 15 | * |
| 16 | * @deprecated This class is introduced only to keep BC with the current static architecture. It will be removed in 3.0. |
| 17 | * - it is global state (that class makes the container a global variable) |
| 18 | * - using the container directly is the "service locator" anti-pattern (which is not dependency injection) |
| 19 | */ |
| 20 | class StaticContainer |
| 21 | { |
| 22 | /** |
| 23 | * @var Container[] |
| 24 | */ |
| 25 | private static $containerStack = array(); |
| 26 | |
| 27 | /** |
| 28 | * Definitions to register in the container. |
| 29 | * |
| 30 | * @var array[] |
| 31 | */ |
| 32 | private static $definitions = array(); |
| 33 | |
| 34 | /** |
| 35 | * @return Container |
| 36 | */ |
| 37 | public static function getContainer() |
| 38 | { |
| 39 | if (empty(self::$containerStack)) { |
| 40 | throw new ContainerDoesNotExistException("The root container has not been created yet."); |
| 41 | } |
| 42 | |
| 43 | return end(self::$containerStack); |
| 44 | } |
| 45 | |
| 46 | public static function clearContainer() |
| 47 | { |
| 48 | self::pop(); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Only use this in tests. |
| 53 | * |
| 54 | * @param Container $container |
| 55 | */ |
| 56 | public static function push(Container $container) |
| 57 | { |
| 58 | self::$containerStack[] = $container; |
| 59 | } |
| 60 | |
| 61 | public static function pop() |
| 62 | { |
| 63 | array_pop(self::$containerStack); |
| 64 | } |
| 65 | |
| 66 | public static function addDefinitions(array $definitions) |
| 67 | { |
| 68 | self::$definitions[] = $definitions; |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Proxy to Container::get() |
| 73 | * |
| 74 | * @param string $name Container entry name. |
| 75 | * @return mixed |
| 76 | * @throws \DI\NotFoundException |
| 77 | */ |
| 78 | public static function get($name) |
| 79 | { |
| 80 | return self::getContainer()->get($name); |
| 81 | } |
| 82 | |
| 83 | public static function getDefinitions() |
| 84 | { |
| 85 | return self::$definitions; |
| 86 | } |
| 87 | } |
| 88 |