Answer the question
In order to leave comments, you need to log in
PHP. Correct approach to create a class to work with sessions?
Hello! I want to implement my add-on for working with sessions in PHP. At this stage, the question arose of how to implement the session_start (); and session_destroy(); . Please tell me in which direction to move! What else can be added to the class? Thank you!
class Session
{
protected function getFront()
{
$front = Front::getInstance();
return $front;
}
public function getSession()
{
//return $this->getFront()->getController();
}
public function __call($name, $args)
{
$key = getUnderscoresSeparatedFormat(substr($name, 3, strlen($name)));
if (strpos($name, 'get') === 0){
if (empty ($args[0])) $args[0] = NULL;
return $this->get($key, $args[0]);
}
if (strpos($name, 'set') === 0){
if (empty($args[0])) $args[0] = NULL;
return $this->set($key, $args[0]);
}
}
public function set($key, $value)
{
if (isset($_SESSION[$key])){
throw new Exception ("Unable to set Session var! " . $key . ' already exists!');
} else {
$_SESSION[$key] = $value;
return true;
}
}
public function get($key, $defaultValue = NULL)
{
if (isset($_SESSION[$key])){
return $_SESSION[$key];
}
return $defaultValue;
}
}
Answer the question
In order to leave comments, you need to log in
The session class does too much for you, everything can be done easier.
<?php
class Session
{
protected function tryLoadSession()
{
if (empty($_SESSION)) {
session_start();
}
}
public function get($name)
{
$this->tryLoadSession();
if (empty($_SESSION[$name])) {
return null;
}
return $_SESSION[$name];
}
public function set($name, $value)
{
$this->tryLoadSession();
$_SESSION[$name] = $value;
}
}
$session = new Session;
$session->get('user_id');
$session->set('user_id', 100500);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question