Using $_SESSION with OOP php -
i need redesign back-end of website , need getting started. original website uses oop, there class "user" used saved data when users log on. serialized , unserialized on each page needed:
// login.php $user = new user($iduser); // ... // @ end of script $_session["user"] = serialize($user); // page $user = unserialize ($_session["user"]);
thus data available on every page user visits. plus, in (almost) every page visited, $_session["user"] updated new data (it’s quite possible page_a.php doesn’t use data page_b.php needs show).
the new design should object oriented. , main problem find don’t know how store $_session["user"] in class method.
i tried use codeigniter, uses session variables cookies, , not need.
any suggestion or link helpful. in advance.
i have no experience codeigniter, can't give specific advise on that. trust others point in right direction if there specific tools available use case in framework. can give insights on how handle basic, vanilla php tough.
if want keep things simple, suggest working sort of app singleton (or auth, or whatever want call it), can handle static data active user. consider following (very basic , untested) code
class app { protected static $instance; public $user; final private __construct() { $user = unserialize($_session['user']); } final private __clone() {} public static getinstance() { if (! self::$instance) { self::$instance = new static; } return self::$instance; } public function __destruct() { $_session["user"] = serialize($this->user); } }
this allow things like:
/* fetch active user */ $user = app::getinstance()->user; /* set active user */ $app = app::getinstance(); $app->user = new user($iduser);
the destruct handler takes care of sending data session when done app object. , since use singleton pattern, there can 1 instance of it, no matter call from. ensures talking same user.
let me know if unclear, or if want me explain further.
Comments
Post a Comment