SettingsService.php
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Settings; |
| 4 | |
| 5 | /** |
| 6 | * Service for registering a new setting. |
| 7 | */ |
| 8 | class SettingsService { |
| 9 | /** |
| 10 | * Holds our registered settings. |
| 11 | * |
| 12 | * @var array |
| 13 | */ |
| 14 | private $settings = []; |
| 15 | |
| 16 | /** |
| 17 | * The Singleton's instance is stored in a static field. This field is an |
| 18 | * array, because we'll allow our Singleton to have subclasses. Each item in |
| 19 | * this array will be an instance of a specific Singleton's subclass. You'll |
| 20 | * see how this works in a moment. |
| 21 | */ |
| 22 | private static $instances = []; |
| 23 | |
| 24 | /** |
| 25 | * The Singleton's constructor should always be private to prevent direct |
| 26 | * construction calls with the `new` operator. |
| 27 | */ |
| 28 | final private function __construct() { } |
| 29 | |
| 30 | /** |
| 31 | * Singletons should not be cloneable. |
| 32 | */ |
| 33 | protected function __clone() { } |
| 34 | |
| 35 | /** |
| 36 | * Singletons should not be restorable from strings. |
| 37 | */ |
| 38 | public function __wakeup() { |
| 39 | throw new \Exception( 'Cannot unserialize a singleton.' ); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * This is the static method that controls the access to the singleton |
| 44 | * instance. On the first run, it creates a singleton object and places it |
| 45 | * into the static field. On subsequent runs, it returns the client existing |
| 46 | * object stored in the static field. |
| 47 | * |
| 48 | * This implementation lets you subclass the Singleton class while keeping |
| 49 | * just one instance of each subclass around. |
| 50 | */ |
| 51 | public static function getInstance() { |
| 52 | $cls = static::class; |
| 53 | if ( ! isset( self::$instances[ $cls ] ) ) { |
| 54 | self::$instances[ $cls ] = new static(); |
| 55 | } |
| 56 | |
| 57 | return self::$instances[ $cls ]; |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Register the setting. |
| 62 | * |
| 63 | * @param string $class Classname to initialize. |
| 64 | */ |
| 65 | public function register( $class ) { |
| 66 | if ( ! class_exists( $class ) ) { |
| 67 | return; |
| 68 | } |
| 69 | |
| 70 | // Create a new instance of the setting. |
| 71 | $registered = new $class(); |
| 72 | |
| 73 | if ( method_exists( $registered, 'register' ) ) { |
| 74 | $registered->register(); |
| 75 | $this->settings[ $class ] = $registered; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * Get all registered settings |
| 81 | * |
| 82 | * @return array |
| 83 | */ |
| 84 | public function getRegisteredSettings() { |
| 85 | return $this->settings; |
| 86 | } |
| 87 | } |
| 88 |