Last active
March 20, 2022 13:32
-
-
Save mavik/bf5c63cb13dce84f078e0920140cea45 to your computer and use it in GitHub Desktop.
Forbidding of creating objects outside factory in PHP with Reflection
This file contains hidden or 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 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