Skip to content

Instantly share code, notes, and snippets.

@mavik
Last active March 20, 2022 13:18
Show Gist options
  • Save mavik/a503f3adf3e20cddb38c88cff99e3f34 to your computer and use it in GitHub Desktop.
Save mavik/a503f3adf3e20cddb38c88cff99e3f34 to your computer and use it in GitHub Desktop.
Forbidding of creating objects outside factory in PHP with debug_backtrace
<?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