shared instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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