Skip to content

Instantly share code, notes, and snippets.

@chadyred
Last active April 25, 2025 06:08
Show Gist options
  • Save chadyred/00c2af75f69ac793810f10227ad9c520 to your computer and use it in GitHub Desktop.
Save chadyred/00c2af75f69ac793810f10227ad9c520 to your computer and use it in GitHub Desktop.
Keep instance
interface F{}
class Article implements F
{
public function __construct(public readonly string $foo)
{
}
}
interface FactoryAwareInterface{
public static function getInstance(string $className, ...$with): F;
}
trait ClassInstanceCached
{
private static object $real;
public static function getInstance(string $className, ...$with): F
{
return self::$real ??= (new static())->build($className, ...$with);
}
}
class FactoryAware implements FactoryAwareInterface
{
use ClassInstanceCached;
public static function build(string $className, ...$with): F
{
if(is_a($className, F::class, true)) {
return new $className(...$with);
}
throw new RuntimeError("Not a F");
}
}
$a = FactoryAware::getInstance(Article::class, "foo");
$sameAsA = FactoryAware::getInstance(Article::class, "foo");
$sameAsABis = FactoryAware::getInstance(Article::class, "foo");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment