StateManager

The StateManager class acts as the application's memory. It handles state persistence across HTTP requests using sessions, synchronizes data with the global scope, and provides a subscription model for reactive updates.

Lifecycle & Persistence

The StateManager is designed to work seamlessly with PulsePoint's "Wire" requests.

  • It loads existing state from the Session.
  • If the request is NOT a Wire request (a hard page load), it resets the state to ensure a clean slate.
  • If it IS a Wire request, state persists, maintaining the user's context.

Core Methods

static getState(?string $key = null, mixed $initialValue = null): mixed

Retrieves data from the state. If $key is null, returns the entire state object.

Feature: If the stored value is an array, it returns an ArrayObject. This allows you to access data using object syntax (e.g., $state->user->name).
static setState(string $key, mixed $value = null): void

Updates the state map and immediately persists it to $_SESSION.

Syncing: If a global variable with the same name exists ($GLOBALS[$key]), this method updates it automatically, ensuring your local variables stay in sync with the centralized state.
static resetState(?string $key = null): void

Clears the state. If a key is provided, only that key is set to null. If no key is provided, the entire state array is emptied.

static subscribe(callable $listener): callable

Registers a callback that triggers whenever the state changes. Returns a closure that can be executed to unsubscribe.

Example Usage

Managing a Counter

<?php

use PP\StateManager;

// 2. Get current value (default to 0)
$count = StateManager::getState('count', 0);

// 3. Define Logic
function increment() {
    // Get current, add 1, save back to state
    $current = StateManager::getState('count', 0);
    StateManager::setState('count', $current + 1);
}

function reset() {
    StateManager::resetState('count');
}

?>

<!-- View -->
<div class="p-4 border rounded">
    <h2>Count: <?= $count ?></h2>
</div>

Working with Arrays

<?php
use PP\StateManager;

// Storing complex data
StateManager::setState('user', [
    'name' => 'Jefferson',
    'role' => 'Admin'
]);

// Retrieving (Returns ArrayObject)
$user = StateManager::getState('user');

// Access properties like an object
echo $user->name; // Outputs: Jefferson
?>