M
M
Mick Coder2014-12-20 18:17:10
PHP
Mick Coder, 2014-12-20 18:17:10

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

2 answer(s)
J
japanxt, 2014-12-20
@lbondodesc

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);

Example code, it may not work

F
FanatPHP, 2014-12-20
@FanatPHP

The structure of the code is no good. The architecture should be modeled after this framework: https://github.com/Herzult/SimplePHPEasyPlus

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question