DEV Community

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

Posted on • Edited on

16 6

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!

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay