PHP - Create a simple session wrapper class
F.R Michel
Posted on November 14, 2020
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;
}
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);
}
}
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
$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
Simple and easy!
https://github.com/devcoder-xyz/php-session-manager
💖 💪 🙅 🚩
F.R Michel
Posted on November 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.