| 1 |
<?php namespace TierPricingTable\Core; |
| 2 |
|
| 3 |
use Exception; |
| 4 |
use TierPricingTable\Admin\Notifications\Notifications; |
| 5 |
use TierPricingTable\Admin\Tips\TipsManager; |
| 6 |
use TierPricingTable\Settings\Settings; |
| 7 |
|
| 8 |
class ServiceContainer { |
| 9 |
|
| 10 |
private $services = array(); |
| 11 |
|
| 12 |
private static $instance; |
| 13 |
|
| 14 |
private function __construct() {} |
| 15 |
|
| 16 |
public static function getInstance(): self { |
| 17 |
if ( is_null( self::$instance ) ) { |
| 18 |
self::$instance = new self(); |
| 19 |
} |
| 20 |
|
| 21 |
return self::$instance; |
| 22 |
} |
| 23 |
|
| 24 |
public function add( $name, $instance ) { |
| 25 |
$this->services[ $name ] = $instance; |
| 26 |
} |
| 27 |
|
| 28 |
public function initService( $className, $dependencies = [] ) { |
| 29 |
|
| 30 |
$className = apply_filters( 'tiered_pricing_table/container/service_instance', $className ); |
| 31 |
|
| 32 |
$this->add( $className, new $className( ...$dependencies ) ); |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Get service |
| 37 |
* |
| 38 |
* @param $name |
| 39 |
* |
| 40 |
* @return mixed |
| 41 |
* @throws Exception |
| 42 |
*/ |
| 43 |
public function get( $name ) { |
| 44 |
if ( ! empty( $this->services[ $name ] ) ) { |
| 45 |
return $this->services[ $name ]; |
| 46 |
} |
| 47 |
|
| 48 |
throw new Exception( 'Undefined service' ); |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Get fileManager |
| 53 |
* |
| 54 |
* @return FileManager |
| 55 |
*/ |
| 56 |
public function getFileManager(): ?FileManager { |
| 57 |
try { |
| 58 |
return $this->get( 'fileManager' ); |
| 59 |
} catch ( Exception $e ) { |
| 60 |
return null; |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Get Settings |
| 66 |
* |
| 67 |
* @return Settings |
| 68 |
*/ |
| 69 |
public function getSettings(): ?Settings { |
| 70 |
try { |
| 71 |
return $this->get( 'settings' ); |
| 72 |
} catch ( Exception $e ) { |
| 73 |
return null; |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* Get AdminNotifier |
| 79 |
* |
| 80 |
* @return AdminNotifier |
| 81 |
*/ |
| 82 |
public function getAdminNotifier(): ?AdminNotifier { |
| 83 |
try { |
| 84 |
return $this->get( 'adminNotifier' ); |
| 85 |
} catch ( Exception $e ) { |
| 86 |
return null; |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
/** |
| 91 |
* Get Cache |
| 92 |
* |
| 93 |
* @return Cache |
| 94 |
*/ |
| 95 |
public function getCache(): ?Cache { |
| 96 |
try { |
| 97 |
return $this->get( 'cache' ); |
| 98 |
} catch ( Exception $e ) { |
| 99 |
return null; |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
public function getNotificationManager(): ?Notifications { |
| 104 |
try { |
| 105 |
return $this->get( Notifications::class ); |
| 106 |
} catch ( Exception $e ) { |
| 107 |
return null; |
| 108 |
} |
| 109 |
} |
| 110 |
} |
| 111 |
|