| @@ -1,39 +1,36 @@ | ||
| 1 | -<?php | |
| 2 | - | |
| 3 | -namespace TableBuilder\Traits; | |
| 4 | - | |
| 5 | -/** | |
| 6 | - * Trait for making singleton instance | |
| 7 | - * This is a factory singleton | |
| 8 | - * | |
| 9 | - * @package Gutenkit\Traits | |
| 10 | - */ | |
| 11 | -trait Singleton { | |
| 12 | - /** | |
| 13 | - * The Singleton's instance is stored in a static field. This field is an | |
| 14 | - * array, because we'll allow our Singleton to have subclasses. Each item in | |
| 15 | - * this array will be an instance of a specific Singleton's subclass. You'll | |
| 16 | - * see how this works in a moment. | |
| 17 | - */ | |
| 18 | - private static $instances = array(); | |
| 19 | - | |
| 20 | - /** | |
| 21 | - * This is the static method that controls the access to the singleton | |
| 22 | - * instance. On the first run, it creates a singleton object and places it | |
| 23 | - * into the static field. On subsequent runs, it returns the client existing | |
| 24 | - * object stored in the static field. | |
| 25 | - * | |
| 26 | - * This implementation lets you subclass the Singleton class while keeping | |
| 27 | - * just one instance of each subclass around. | |
| 28 | - * | |
| 29 | - * @return object | |
| 30 | - * @since 1.0.0 | |
| 31 | - */ | |
| 32 | - public static function instance() { | |
| 33 | - $class = get_called_class(); | |
| 34 | - if ( ! isset( self::$instances[$class] ) ) { | |
| 35 | - self::$instances[$class] = new $class(); | |
| 36 | - } | |
| 37 | - return self::$instances[$class]; | |
| 38 | - } | |
| 39 | -} | |
| 1 | +<?php | |
| 2 | +/** | |
| 3 | + * Generic singleton trait for per-class shared instances | |
| 4 | + * | |
| 5 | + * @package TableKit | |
| 6 | + */ | |
| 7 | + | |
| 8 | +namespace TableBuilder\Traits; | |
| 9 | + | |
| 10 | +/** | |
| 11 | + * Generic singleton trait: gives any class a shared instance() accessor | |
| 12 | + * keyed by class name, so subclasses don't each need to reimplement it. | |
| 13 | + * | |
| 14 | + * @package TableBuilder\Traits | |
| 15 | + */ | |
| 16 | +trait Singleton { | |
| 17 | + /** | |
| 18 | + * Shared instances, keyed by class name. | |
| 19 | + * | |
| 20 | + * @var array | |
| 21 | + */ | |
| 22 | + private static $instances = array(); | |
| 23 | + | |
| 24 | + /** | |
| 25 | + * Gets (and lazily creates) the shared instance of the using class. | |
| 26 | + * | |
| 27 | + * @return static The shared instance. | |
| 28 | + */ | |
| 29 | + public static function instance() { | |
| 30 | + $class = get_called_class(); | |
| 31 | + if ( ! isset( self::$instances[ $class ] ) ) { | |
| 32 | + self::$instances[ $class ] = new $class(); | |
| 33 | + } | |
| 34 | + return self::$instances[ $class ]; | |
| 35 | + } | |
| 36 | +} | |