Sledgehammer Framework

Singleton

Adds singleton behavior to a class.

Example: Get the default instance $db = Connection::instance();

Example: Set/overwrite the default instance Connection::$instances['default'] = new Connection('mysql://localhost'));

Example: Lazily configure the singleton via closure Connection::$instances['default'] = function () { return new Connection('mysql://localhost'); };

Example: Lazily configure the singleton in the class class MyClass { use Singleton; protected static defaultInstance() { return new MyClass(['configured' => 'with defaults']); } }

Table of Contents

$instances  : array<string|int, static>
The instances that are accessible by class::instance() [ 'id' => instance, // direct mapping to an instance 'id2' => 'id' // indirect mapping to an instance 'id3' => function () { return new Sington() } // lazy creation of an instance.
instance()  : static
Get the singleton instance.
defaultInstance()  : static
Create a default instance.

Properties

$instances

The instances that are accessible by class::instance() [ 'id' => instance, // direct mapping to an instance 'id2' => 'id' // indirect mapping to an instance 'id3' => function () { return new Sington() } // lazy creation of an instance.

public static array<string|int, static> $instances = []

].

Methods

instance()

Get the singleton instance.

public static instance([string $identifier = 'default' ]) : static
Parameters
$identifier : string = 'default'

The identifier (string),

Return values
static

defaultInstance()

Create a default instance.

protected static defaultInstance() : static

Override in the (sub)class to create an instance with default parameters.

Return values
static

Search results