| 1 |
<?php |
| 2 |
/** |
| 3 |
* Singleton trait |
| 4 |
* |
| 5 |
* @package Tableberg |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Tableberg\includes\traits; |
| 9 |
|
| 10 |
/** |
| 11 |
* Singleton trait. |
| 12 |
*/ |
| 13 |
trait Singleton_Trait { |
| 14 |
/** |
| 15 |
* Class instance options. |
| 16 |
* |
| 17 |
* @private |
| 18 |
* @var array |
| 19 |
*/ |
| 20 |
private $class_options = array(); |
| 21 |
|
| 22 |
/** |
| 23 |
* Manager base instance. |
| 24 |
* |
| 25 |
* @var null|object |
| 26 |
*/ |
| 27 |
protected static $instance = null; |
| 28 |
|
| 29 |
/** |
| 30 |
* Class instance constructor. |
| 31 |
* |
| 32 |
* @param array $const_args constructor args. |
| 33 |
*/ |
| 34 |
protected function __construct( $const_args = array() ) { |
| 35 |
$this->class_options = $const_args; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Get class instance. |
| 40 |
* |
| 41 |
* @param array $constructor_args constructor args. |
| 42 |
* @param string|null $class_name class name to create instance. |
| 43 |
* |
| 44 |
* @return object object instance |
| 45 |
*/ |
| 46 |
public static function get_instance( $constructor_args = array(), $class_name = null ) { |
| 47 |
if ( is_null( static::$instance ) ) { |
| 48 |
static::create_instance( $constructor_args, $class_name ); |
| 49 |
} |
| 50 |
|
| 51 |
return static::$instance; |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Force create instance of singleton if it there is none. |
| 56 |
* |
| 57 |
* @param array $constructor_args constructor args. |
| 58 |
* @param string|null $class_name class name to create instance. |
| 59 |
* |
| 60 |
* @return void |
| 61 |
*/ |
| 62 |
final protected static function create_instance( $constructor_args = array(), $class_name = null ) { |
| 63 |
if ( is_null( static::$instance ) ) { |
| 64 |
$class_name = __CLASS__; |
| 65 |
|
| 66 |
if ( ! is_null( $class_name ) ) { |
| 67 |
$class_name = class_exists( $class_name ) ? $class_name : __CLASS__; |
| 68 |
} |
| 69 |
|
| 70 |
static::$instance = new $class_name( $constructor_args ); |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
|