Skip to content

Commit

Permalink
Allow many singletons
Browse files Browse the repository at this point in the history
  • Loading branch information
idmontie committed Sep 18, 2015
1 parent b4eeb42 commit a1ba21e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
6 changes: 3 additions & 3 deletions src/configuration/configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ class Configuration extends Singleton {
public $attributes;

public static function set_configuration_path( $path ) {
self::$instance = new Configuration( $path );
self::set_instance( new self( $path ) );
}

public static function reset() {
self::$instance = null;
self::$instances[ self::class ] = null;
}

public function get( $key, $default = null ) {
Expand All @@ -36,7 +36,7 @@ protected function __construct( $path = '.env' ) {
$configuration = '';

if ( file_exists( $path ) ) {
$configuration = @file_get_contents( $path );
$configuration = @file_get_contents( $path );
}

if ( ! empty( $configuration ) ) {
Expand Down
24 changes: 17 additions & 7 deletions src/singleton/singleton.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,25 @@
namespace Nectary;

abstract class Singleton {
protected static $instance = null;
protected function __construct() { }

protected function __clone() { }
protected static $instances = array();
protected function __construct() {}
protected function __clone() {}
public function __wakeup() {
throw new Exception( 'Cannot unserialize singleton' );
}

public static function get_instance() {
if ( ! isset( static::$instance ) ) {
static::$instance = new static;
$cls = get_called_class(); // late-static-bound class name
if ( ! isset( self::$instances[ $cls ] ) ) {
self::$instances[ $cls ] = new static;
}
return static::$instance;

return self::$instances[ $cls ];
}

public static function set_instance( $instance ) {
$cls = get_called_class();

self::$instances[ $cls ] = $instance;
}
}

0 comments on commit a1ba21e

Please sign in to comment.