Avoid the Singleton
A static getInstance() singleton hides a piece of global mutable state behind a call you can't see in the constructor. Every class that reaches for it shares the same object, so a test that calls enable('new_checkout') leaves the flag on for every test that runs after it. You can't substitute a fake either, because the dependency never travels through a parameter.
Don't do this
<?php
declare(strict_types=1);
namespace App\Reporting;
final class FeatureFlags
{
private static ?self $instance = null;
/** @var array<string, bool> */
private array $flags = [];
public static function getInstance(): self
{
return self::$instance ??= new self();
}
public function enable(string $name): void
{
$this->flags[$name] = true;
}
public function isEnabled(string $name): bool
{
return $this->flags[$name] ?? false;
}
}
final class CheckoutController
{
public function store(): void
{
if (FeatureFlags::getInstance()->isEnabled('new_checkout')) {
// ...
}
}
}Do this instead
Register one shared instance in the container and inject it:
<?php
declare(strict_types=1);
namespace App\Reporting;
final class FeatureFlags
{
/** @var array<string, bool> */
private array $flags = [];
public function enable(string $name): void
{
$this->flags[$name] = true;
}
public function isEnabled(string $name): bool
{
return $this->flags[$name] ?? false;
}
}<?php
declare(strict_types=1);
namespace App\Providers;
use App\Reporting\FeatureFlags;
use Illuminate\Support\ServiceProvider;
final class FeatureFlagsServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(FeatureFlags::class);
}
}<?php
declare(strict_types=1);
namespace App\Reporting;
final readonly class CheckoutController
{
public function __construct(private FeatureFlags $flags) {}
public function store(): void
{
if ($this->flags->isEnabled('new_checkout')) {
// ...
}
}
}The container still hands every class the same FeatureFlags within one application, but the dependency now shows in the constructor. Laravel's TestCase builds a fresh application for each test (refreshApplication()), so the singleton starts empty every time and a flag enabled in one test cannot reach the next. A test that needs specific flags binds its own FeatureFlags before resolving the controller.