Skip to content

Instantly share code, notes, and snippets.

@Yarkhan
Last active January 3, 2016 09:09
Show Gist options
  • Save Yarkhan/8ad705c8ee436846e4e5 to your computer and use it in GitHub Desktop.
Save Yarkhan/8ad705c8ee436846e4e5 to your computer and use it in GitHub Desktop.
Protótipo classe para gerenciar sessão.
<?php
namespace Yarkhan\SessionManager;
class Session{
//The key on $_SESSION to store data
static $sess_name = 'YarkhanSessionManager';
private static $sess;
static function isActive()
{
return !empty($_SESSION[self::$sess_name]['start_time']);
}
//start the session!
static function start()
{
session_start();
self::$sess =& $_SESSION[self::$sess_name];
if(self::isActive())
{
self::$sess['last_update'] = time();
}
else {
self::$sess['start_time'] = time();
self::$sess['last_update'] = time();
}
}
/**
* Return time() of when the session started
* @return [mixed] time() when session is active, or false
*/
static function start_time()
{
return self::isActive() ? self::$sess['start_time'] : false;
}
/**
* Return
* @return mixed time() of the session last update, false if is not active
*/
static function last_update()
{
return self::isActive() ? self::$sess['last_update']:false;
}
/**
* Round house kick on session data
* @return void
*/
static function destroy()
{
if(!empty(self::$sess)) unset($_SESSION[self::$sess_name]);
}
/**
* setFlash. Data that is going to be destroyed the next time is read
* @param $key
* @param $value
* @return void
*/
static function setFlash($key,$value)
{
if(!self::isActive()) return;
self::$sess['_flash'][$key] = $value;
}
/**
* Get a flash value that has been stored. Data is destroyed unless
* $keep is set to true
* @param str $key key on flashdata
* @param boolean $keep if data should be destroyed after reading
* @return mixed Value stored in flashdata $key or false if session is not
* active or $key hasn't been defined
*/
static function getFlash($key,$keep = false)
{
if(!self::isActive() or empty(self::$sess['_flash'][$key])) return false;
$flash = self::$sess['_flash'][$key];
if(!$keep) unset(self::$sess['_flash'][$key]);
return $flash;
}
/**
* Data that will be stored until the session ends
* @param str $key key on userdata
* @param mixed $value value on userdata
*/
static function setUserdata($key,$value)
{
if(!self::isActive()) return;
self::$sess['_userdata'][$key] = $value;
}
/**
* Get data stored on userdata
* @param str $key $key on userdata
* @return mixed return value of $key in userdata. False
* if session is not active or $key is not set.
*/
static function getUserdata($key)
{
if(!self::isActive()) return;
if(!empty(self::$sess['_userdata'][$key]))
{
return self::$sess['_userdata'][$key];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment