Skip to content

Instantly share code, notes, and snippets.

@mavik
Last active March 20, 2022 13:32
Show Gist options
  • Save mavik/bf5c63cb13dce84f078e0920140cea45 to your computer and use it in GitHub Desktop.
Save mavik/bf5c63cb13dce84f078e0920140cea45 to your computer and use it in GitHub Desktop.
Forbidding of creating objects outside factory in PHP with Reflection
<?php
class ClassA
{
public const FRIEND_CLASSES = [Factory::class];
protected function __construct() {}
}
trait Constructor
{
protected function createObject(string $className, array $args = [])
{
if (!in_array(static::class, $className::FRIEND_CLASSES)) {
throw new \Exception("Call to private or protected {$className}::__construct() from invalid context");
}
$reflection = new ReflectionClass($className);
$constructor = $reflection->getConstructor();
$constructor->setAccessible(true);
$object = $reflection->newInstanceWithoutConstructor();
$constructor->invokeArgs($object, $args);
return $object;
}
}
class Factory
{
use Constructor;
public function createA(): ClassA
{
return $this->createObject(ClassA::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment