Skip to content

Session

The Session plugin provides HTTP session management with support for flash messages, abstracting session handling from the underlying implementation.

Two adapters are available:

  • NativeSession uses PHP native session functions (session_start(), $_SESSION) with zero dependencies.
  • OdanSession wraps the Odan Session library for feature-rich session management.

Why Use It

Session management is required for user authentication state, flash messages, and temporary data storage between requests. The plugin provides a clean interface that can be wrapped in an application-level service for domain-specific operations.

Usage

Basic session operations:

$this->session->set('user_id', $userId);
$value = $this->session->get('user_id');
$this->session->delete('user_id');

Flash messages for post-redirect-get patterns:

$this->session->addFlashMessage('success', 'Book created successfully!');
$messages = $this->session->getFlash()->all();

Security operations:

$this->session->regenerateId();  // Prevent session fixation
$this->session->destroy();       // Clear session on logout

An application service typically wraps the session for domain-specific operations:

final readonly class SessionService
{
    public function setUserAuthenticated(IdInterface $userId): void
    {
        $this->session->set('user_id', $userId->getValue());
        $this->session->regenerateId();
    }
}

Testing

Session behavior can be tested by mocking SessionInterface or using the actual adapter with test configuration. Flash messages are commonly verified through integration tests.

See Also