Skip to content

Instantly share code, notes, and snippets.

@timothyjensen
Last active July 8, 2018 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timothyjensen/34398774898c328f70f6f6ab80e76d42 to your computer and use it in GitHub Desktop.
Save timothyjensen/34398774898c328f70f6f6ab80e76d42 to your computer and use it in GitHub Desktop.
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