class-container.php
1 year ago
class-loader.php
1 year ago
class-rest-api.php
1 year ago
class-utilities.php
5 months ago
plugins-list.php
5 months ago
class-container.php
64 lines
| 1 | <?php |
| 2 | /** |
| 3 | * The Container class used for DI. |
| 4 | * |
| 5 | * @link https://wpmudev.com/ |
| 6 | * @since 1.0.0 |
| 7 | * |
| 8 | * @author WPMUDEV (https://wpmudev.com) |
| 9 | * @package WPMUDEV/Plugin_Cross_Sell |
| 10 | * |
| 11 | * @copyright (c) 2025, Incsub (http://incsub.com) |
| 12 | */ |
| 13 | |
| 14 | namespace WPMUDEV\Modules\Plugin_Cross_Sell; |
| 15 | |
| 16 | /** |
| 17 | * Dependency Injection Container class. |
| 18 | * |
| 19 | * @since 1.0.0 |
| 20 | */ |
| 21 | class Container { |
| 22 | /** |
| 23 | * Services list. |
| 24 | * |
| 25 | * @var array |
| 26 | */ |
| 27 | private $services = array(); |
| 28 | |
| 29 | /** |
| 30 | * Pushes a service into the container. |
| 31 | * |
| 32 | * @param string $key Service key. |
| 33 | * @param mixed $value Service. |
| 34 | * @return void |
| 35 | */ |
| 36 | public function set( string $key, $value ): void { |
| 37 | $this->services[ $key ] = $value; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Fetches a service from the container. |
| 42 | * |
| 43 | * @param string $key Service key. |
| 44 | * @throws \InvalidArgumentException If service not found. |
| 45 | */ |
| 46 | public function get( string $key ) { |
| 47 | if ( ! isset( $this->services[ $key ] ) ) { |
| 48 | throw new \InvalidArgumentException( esc_html( "Service '{$key}' not found in container." ) ); |
| 49 | } |
| 50 | |
| 51 | return $this->services[ $key ]; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Checks if a service is registered. |
| 56 | * |
| 57 | * @param string $key Service key. |
| 58 | * @return bool |
| 59 | */ |
| 60 | public function has( string $key ): bool { |
| 61 | return isset( $this->services[ $key ] ); |
| 62 | } |
| 63 | } |
| 64 |