Codeigniter Session重构

为了方便使用php的session,我在这里重写了一个简单的session方法。

新建application/libraries/Sessions.php,内容如下:


<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
* Reconstruct the session class
* @author chory
* @version 1.0
* @copyright 2011/6/12
*/
class Sessions{
    private static $instances;
    private static function instance()
    {
        if (empty(self::$instances)){
            @self::$instances = &load_class('session');
        }
        return self::$instances;
    }
    public static function set($key, $value = "")
    {
        self::instance() -> set_userdata(array($key => $value));
    }
    public static function get($key = null)
    {
        if ($key)
        {
            return self::instance() -> userdata($key);
        }
        else
        {
            return self::instance() -> all_userdata();
        }
    }
    public static function _unset($key){
        self::instance() -> unset_userdata($key);
    }
    public static function destroy(){
        self::instance() -> sess_destroy();
    }
}

应用方法:

Sessions::set("username", "admin");

Sessions::get("username");

可以在autoload.php中设置自动加载,或手动调用Sessions

你可能感兴趣的:(Codeigniter Session重构)