PHP code example of kodus / session

1. Go to this page and download the library: Download kodus/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/ */

    

kodus / session example snippets


class UserSession implements SessionModel
{
    private $user_id;
    private $full_name;
    
    public function setUserID(int $user_id)
    {
        $this->user_id = $user_id;
    }
    
    public function getUserID(): int
    {
        return $this->user_id ?: 0;
    }
    
    public function setFullName(string $full_name)
    {
        $this->full_name = $full_name;
    }
    
    public function getFullName(): string
    {
        return $this->full_name ?: "";
    }
        
    public function isEmpty(): bool
    {
        return empty($this->user_id) && empty($this->full_name);
    }
}

/** @var UserSession $user_session */
$user_session = $session->get(UserSession::class);

class UserSession implements SessionModel
{
    private $user_id;

    public function clear()
    {
        unset($this->user_id);
    }

    public function isEmpty(): bool
    {
        return empty($this->user_id);
    }

    // ...
}

$session->clear();

$session->renew();

$storage->delete($session_id);

class Notifications implements SessionModel
{
    private $notifications = [];

    public function add(string $message)
    {
        $this->notifications[] = $message;
    }
    
    public function take()
    {
        $notifications = $this->notifications;
        
        $this->notifications = [];
        
        return $notifications;
    }

    public function isEmpty(): bool
    {
        return count($this->notifications) == 0;
    }
}

use PDO;
use MatthiasMullie\Scrapbook\Adapters\SQLite;
use MatthiasMullie\Scrapbook\Psr16\SimpleCache;
use Kodus\Session\Adapters\SimpleCacheAdapter;
use Kodus\Session\SessionMiddleware;

$connection = new PDO('sqlite:cache.db');

$cache = new SimpleCache(new SQLite($connection));

$storage = new SimpleCacheAdapter($cache);

$service = new SessionService($storage);

$middleware = new SessionMiddleware($service);