PHP code example of joby / smol-session

1. Go to this page and download the library: Download joby/smol-session library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

joby / smol-session example snippets


use Joby\Smol\Session\Session;

// Set values (queued, doesn't lock the session)
Session::set('user_id', 123);
Session::set('username', 'john_doe');

// Increment a counter (queued, doesn't lock the session, will apply to actual value upon commit to avoid race conditions)
Session::increment('page_views');
Session::increment('score', 10);

// Unset values (queued, doesn't lock the session)
Session::unset('temp_data');

// Read values (applies queued updates to cached values for convenience)
$userId = Session::get('user_id');
$views = Session::get('page_views');

// Commit all changes at once atomically, does not reopen session if no changes are queued
Session::commit();

// Can rotate session IDs
Session::rotate();

// Can also destroy the session, deleting all data and unsetting the cookie
Session::destroy();


// Type-safe access with automatic conversion
$userId = Session::getInt('user_id');       // Converts "123" → 123
$price = Session::getFloat('cart_total');   // Converts "19.99" → 19.99
$enabled = Session::getBool('dark_mode');   // Converts "yes" → true
$username = Session::getString('username'); // Converts 123 → "123"

// With defaults for missing values
$limit = Session::getInt('page_limit', 20);
$theme = Session::getString('theme', 'default');
$debug = Session::getBool('debug', false);

// Require values (throw TypeCastException if null/missing)
$

use Joby\Smol\Session\SessionUpdate;

class AppendToArray implements SessionUpdate
{
    public function __construct(public mixed $value) {}

    public function apply(mixed $current_value): array
    {
        $array = is_array($current_value) ? $current_value : [];
        $array[] = $this->value;
        return $array;
    }

    public function isAbsolute(): bool
    {
        return false; // depends on current value
    }
}

// Use with Session::update()
Session::update('items', new AppendToArray('new_item'));