sebastian/global-state
sebastian/global-state snapshots and restores PHP global state (globals, superglobals, ini settings, etc.), extracted from PHPUnit as a standalone component. Useful for test isolation and detecting side effects by capturing state before and after code runs.
This package provides a GlobalStateSnapshot class to capture and restore PHP’s global state — including superglobals ($_GET, $_POST, etc.), $GLOBALS, static properties, and INI settings — which is essential for test isolation in PHPUnit or other test runners. Begin by installing it as a dev dependency:
composer require --dev sebastian/global-state
The primary use case is writing reliable, side-effect-free tests where mutable global state (e.g., database connections, cached values, global variables) must be reset between tests. The entry point is SebastianBergmann\GlobalState\Snapshot — instantiate it with Snapshot::snapshot() to capture the current state, and later call $snapshot->restore() to revert changes.
Snapshot::snapshot() in setUp() or before critical assertions, then restore in tearDown() to enforce isolation.
protected function setUp(): void
{
$this->snapshot = Snapshot::snapshot();
}
protected function tearDown(): void
{
$this->snapshot->restore();
}
Snapshot::snapshot() to specify only which state to snapshot/restore (e.g., Snapshot::snapshot(['globals' => ['$_GET', '$_POST']])). This avoids unnecessary overhead.Snapshot::snapshot(['staticProperties' => ['App\MyClass::class']]).$_SESSION and $_COOKIE are not snapshotted by default (due to side effects like session writes); use snapshotSuperGlobals() explicitly if needed, but be cautious — restoring session state can cause race conditions in concurrent tests.snapshot() (e.g., ['globals' => ['$_ENV']]). Profile Snapshot::snapshot() — large $GLOBALS or complex objects can slow tests.$this->dynamic = 'value') may not behave as expected.--process-isolation may suffice for simple cases; sebastian/global-state shines when you need fine-grained state control or non-PHPUnit test runners.restore() in a try/finally if not using tearDown() to guarantee cleanup on early returns/failures:
try {
$snapshot = Snapshot::snapshot();
// ... test logic
} finally {
$snapshot?->restore(); // safe even if $snapshot is null
}
How can I help you explore Laravel packages today?