DEV Community

Cover image for PHP - Create a simple session wrapper class
F.R Michel
F.R Michel

Posted on

PHP - Create a simple session wrapper class

PHP version required 7.3

Manage your session without use directly $_Session global variable

Let's create the interface.

<?php

namespace DevCoder;

interface SessionInterface
{
    /**
     * @param string $key
     * @return mixed
     */
    public function get(string $key);

    /**
     * @param string $key
     * @param mixed $value
     * @return SessionInterface
     */
    public function set(string $key, $value): self;

    public function remove(string $key): void;

    public function clear(): void;

    public function has(string $key): bool;
}
Enter fullscreen mode Exit fullscreen mode

Let's create the class that will manage session.

<?php

namespace DevCoder;

class SessionManager implements SessionInterface
{

    public function __construct(?string $cacheExpire = null, ?string $cacheLimiter = null)
    {
        if (session_status() === PHP_SESSION_NONE) {

            if ($cacheLimiter !== null) {
                session_cache_limiter($cacheLimiter);
            }

            if ($cacheExpire !== null) {
                session_cache_expire($cacheExpire);
            }

            session_start();
        }
    }

    /**
     * @param string $key
     * @return mixed
     */
    public function get(string $key)
    {
        if ($this->has($key)) {
            return $_SESSION[$key];
        }

        return null;
    }

    /**
     * @param string $key
     * @param mixed $value
     * @return SessionManager
     */
    public function set(string $key, $value): SessionInterface
    {
        $_SESSION[$key] = $value;
        return $this;
    }

    public function remove(string $key): void
    {
        if ($this->has($key)) {
            unset($_SESSION[$key]);
        }
    }

    public function clear(): void
    {
        session_unset();
    }

    public function has(string $key): bool
    {
        return array_key_exists($key, $_SESSION);
    }

}
Enter fullscreen mode Exit fullscreen mode

How to use ?

$session = new \DevCoder\SessionManager();
$session->set('token', 'hash');

var_dump($session->get('token'));
// hash
$session->remove('token');
var_dump($session->get('token'));
// NULL
Enter fullscreen mode Exit fullscreen mode
$session = new \DevCoder\SessionManager();
$session->set('date', new \DateTime());
var_dump($session->get('date'));
// class DateTime#2 (3) {
//  public $date =>
//  string(26) "2020-11-14 22:17:39.128909"
//  public $timezone_type =>
//  int(3)
//  public $timezone =>
//  string(13) "Europe/Berlin"
}

$session->clear();
var_dump($session->get('date'));
// NULL
Enter fullscreen mode Exit fullscreen mode

Simple and easy!
https://github.com/devcoder-xyz/php-session-manager

Top comments (0)