State Manager

The StateManager class acts as your application's short-term memory. It persists data across HTTP requests via sessions, synchronizes with the global scope, and powers the reactive updates in PulsePoint.

Lifecycle & Persistence

The StateManager intelligently detects the type of request to determine persistence strategy.

  • Wire Request: State persists seamlessly.
  • Hard Page Load: State resets for a clean slate.

Global Sync

When you call setState, the manager automatically updates the corresponding PHP $GLOBALS variable. This ensures your local logic and the centralized state never drift apart.

Core Methods

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

Retrieves data. If the stored value is an array, it returns an ArrayObject, allowing object-style access (e.g., $state->user->name).

Working with Arrays

Since arrays are converted to Objects, if you need a raw PHP array (e.g., for array_map or foreach), use the getArrayCopy() method.

$menuItems = StateManager::getState('menuItems')->getArrayCopy() ?? [];
static setState(string $key, mixed $value): void

Updates the state map and immediately persists it to $_SESSION. It also syncs with the Global scope.

static resetState(?string $key = null): void

Clears the state. If a key is provided, only that key is removed. If null, the entire state is wiped.

Example Usage

Basic Primitives

Counter Logic
<?php
use PP\StateManager;

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

function increment() {
    $current = StateManager::getState('count', 0);
    StateManager::setState('count', $current + 1);
}
?>

<div>Count: <?= $count ?></div>

Complex Arrays

Array Handling
<?php
use PP\StateManager;

StateManager::setState('menuItems', [
    'Home', 'About', 'Contact'
]);

// Retrieve as Object
$obj = StateManager::getState('menuItems');

// Retrieve as Array (Important!)
$list = $obj->getArrayCopy() ?? [];

foreach ($list as $item) {
    echo $item;
}
?>