Last active
March 20, 2022 13:18
-
-
Save mavik/a503f3adf3e20cddb38c88cff99e3f34 to your computer and use it in GitHub Desktop.
Forbidding of creating objects outside factory in PHP with debug_backtrace
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 | |
trait FactoryChecking | |
{ | |
protected function checkFactory(string $factoryClass): void | |
{ | |
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); | |
foreach($trace as $traceItem) { | |
if ($traceItem['class'] == $factoryClass) { | |
return; | |
} | |
} | |
throw new Exception('Cannot create class ' . static::class . ' outside of factory'); | |
} | |
} | |
class ClassA | |
{ | |
use FactoryChecking; | |
public function __construct() | |
{ | |
$this->checkFactory(Factory::class); | |
} | |
} | |
class Factory | |
{ | |
public function create(): ClassA | |
{ | |
return new ClassA(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment