Session.php 2.08 KB
<?php
/**
 * Created by PhpStorm.
 * User: Zip
 * Date: 14/12/26
 * Time: 上午12:39
 */

namespace Hood;

use Hood\Core\Session\SessionNamespace;
use Hood\Core\Session\CacheSession;
use Hood\Core\Session\FileSession;
use Hood\Core\Session\RpcSession;

class Session
{

    private static $_session = null;

    /**
     * 开启Session并设置NameSpace
     * @param $namespace
     * @return SessionNamespace
     */
    static public function start($namespace = 'session_default', $sessionName = null, $domain = null)
    {
        if (self::isSessionStarted() == false || self::$_session == null) {
            self::$_session = new CacheSession($sessionName, $domain);
            session_start();
        }
        return new SessionNamespace ($namespace);
    }

    /**
     * 开启Session并设置NameSpace,使用File
     * @param $namespace
     * @return SessionNamespace
     */
    static public function fileStart($namespace = 'session_default')
    {
        if (self::isSessionStarted() == false || self::$_session == null) {
            self::$_session = new FileSession();
            session_start();
        }
        return new SessionNamespace ($namespace);
    }

    /**
     * @param $serviceUrl
     * @param string $namespace
     * @return SessionNamespace
     */
    static public function service($serviceUrl, $namespace = 'session_default', $sessionName = null)
    {
        if (self::isSessionStarted() == false || self::$_session == null) {
            self::$_session = new RpcSession($serviceUrl);
            self::$_session->setSessionName($sessionName);
            session_start();
        }
        return new SessionNamespace ($namespace);
    }

    /**
     * 检查Session是否开启
     * @return bool
     */
    static private function isSessionStarted()
    {
        if (php_sapi_name() !== 'cli') {
            if (version_compare(phpversion(), '5.4.0', '>=')) {
                return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
            } else {
                return session_id() === '' ? FALSE : TRUE;
            }
        }
        return false;
    }
}