Skip to content

Instantly share code, notes, and snippets.

@timothyjensen

timothyjensen/saredInstances.php Secret

Last active Jul 8, 2018
Embed
What would you like to do?
shared instances
<?php
/**
* Class SomeClass
*
* @package TimJensen
*/
class SomeClass {
protected $one;
protected $two;
protected $three;
public function __construct( $one, $two ) {
$this->one = $one;
$this->two = $two;
}
public function setThree( $three ) {
$this->three = $three;
}
}
/**
* Class ClassFactory
*
* @package TimJensen
*/
class ClassFactory {
/**
* Holds the shared class instances.
*
* @var array
*/
protected static $instances = [];
/**
* Makes a new instance of the class if one has not already been set.
*
* @param string $class_name Fully qualified name of the class to instantiate.
* @param array $args Arguments passed to the class constructor.
* @return mixed|null
*/
public static function make( string $class_name, $args = [] ) {
if ( ! isset( self::$instances[ $class_name ] ) ) {
try {
$reflection_class = new \ReflectionClass( $class_name );
$class_instance = $reflection_class->newInstanceArgs( $args );
self::$instances[ $class_name ] = $class_instance;
} catch ( \Exception $e ) {
trigger_error( $e->getMessage(), E_USER_ERROR );
} catch ( \ArgumentCountError $e ) {
trigger_error( $e->getMessage(), E_USER_ERROR );
}
}
return self::$instances[ $class_name ] ?? null;
}
/**
* Returns the shared instance of the specified class.
*
* @param string $class_name Fully qualified name of the class instance to retrieve.
* @return mixed|null
*/
public static function get( string $class_name ) {
return self::$instances[ $class_name ] ?? null;
}
}
var_dump( ClassFactory::make( SomeClass::class, [ 'one', 'two' ] ) );
/** @var SomeClass $some_class */
$some_class = ClassFactory::get( SomeClass::class );
$some_class->setThree( 'three' );
var_dump( ClassFactory::get( SomeClass::class ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.