SessionManager is the main API. It implements SessionInterface and delegates persistence to a SessionDriverInterface.
Related pages:
use CommonPHP\Session\SessionManager;
$session = new SessionManager();To configure the native driver in one step:
$session = SessionManager::native(
options: ['cookie_lifetime' => 3600],
name: 'APPSESSID',
);To use a custom driver instance:
$session = new SessionManager($driver);$session->start();
$session->regenerateId();
$session->save();regenerateId(false) keeps the old backend record when the driver supports that behavior.
$session->set('user_id', 42);
$userId = $session->get('user_id');
$removed = $session->remove('user_id');Root data methods:
get(string $key, mixed $default = null): mixedset(string $key, mixed $value): statichas(string $key): boolremove(string $key, mixed $default = null): mixedpull(string $key, mixed $default = null): mixedreplace(array $values): staticall(): arrayclear(): static
has() uses array_key_exists(), so keys with null values still exist.
The root bag is useful when an API expects a SessionBagInterface.
$bag = $session->bag();
$bag->set('user_id', 42);The root bag points at the whole session payload.
Named bags point at a single namespace:
$profile = $session->bag('profile');
$profile->set('display_name', 'Ada');
$profile->set('timezone', 'Europe/London');If a namespace already exists and is not an array, CorruptSessionDataException is thrown. This protects callers from silently overwriting unrelated scalar data.
$flash = $session->flash();
$flash->add('success', 'Saved.');
$flash->add('success', 'Queued for review.');
$messages = $flash->get('success');Flash data is stored in the _flash namespace by default. Pass a custom namespace when a package needs its own flash channel:
$session->flash('_admin_flash')->add('warning', 'Impersonation enabled.');Drivers can be supplied as instances:
$session->useDriver($driver);Or by class name before the session starts:
$session->setDriver(AppSessionDriver::class, [
'connectionName' => 'primary',
]);Constructor arguments are passed with PHP named argument unpacking, so the array keys should match the driver constructor parameter names.