CDbHttpSession

CDbHttpSession

Yii Framework v1.1.10 类参考

CDbHttpSession

system.web
继承 class CDbHttpSession » CHttpSession » CApplicationComponent » CComponent
实现 Countable, ArrayAccess, Traversable, IteratorAggregate, IApplicationComponent
源自 1.0
版本 $Id: CDbHttpSession.php 3426 2011-10-25 00:01:09Z alexander.makarow $
源码 framework/web/CDbHttpSession.php
CDbHttpSession extends CHttpSession by using database as session data storage.

CDbHttpSession stores session data in a DB table named 'YiiSession'. The table name can be changed by setting sessionTableName. If the table does not exist, it will be automatically created if autoCreateSessionTable is set true.

The following is the table structure:

CREATE TABLE YiiSession
(
    id CHAR(32) PRIMARY KEY,
    expire INTEGER,
    data TEXT
)


CDbHttpSession relies on PDO to access database.

By default, it will use an SQLite3 database named 'session-YiiVersion.db' under the application runtime directory. You can also specify connectionID so that it makes use of a DB application component to access database.

When using CDbHttpSession in a production server, we recommend you pre-create the session DB table and set autoCreateSessionTable to be false. This will greatly improve the performance. You may also create a DB index for the 'expire' column in the session table to further improve the performance.

公共属性

隐藏继承属性

属性类型描述定义在
autoCreateSessionTable boolean whether the session DB table should be automatically created if not exists. CDbHttpSession
autoStart boolean whether the session should be automatically started when the session application component is initialized, defaults to true. CHttpSession
behaviors array 这个应用组件附加的行为。 这此行为将在应用组件调用init时附加在应用组件上。 请参照CModel::behaviors如何指定此属性值。 CApplicationComponent
connectionID string the ID of a CDbConnection application component. CDbHttpSession
cookieMode string how to use cookie to store session ID. CHttpSession
cookieParams array the session cookie parameters. CHttpSession
count integer Returns the number of items in the session. CHttpSession
gCProbability integer the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. CHttpSession
isInitialized boolean 检查应用组件是否已经初始化。 CApplicationComponent
isStarted boolean whether the session has started CHttpSession
iterator CHttpSessionIterator Returns an iterator for traversing the session variables. CHttpSession
keys array the list of session variable names CHttpSession
savePath string the current session save path, defaults to '/tmp'. CHttpSession
sessionID string the current session ID CHttpSession
sessionName string the current session name CHttpSession
sessionTableName string the name of the DB table to store session content. CDbHttpSession
timeout integer the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds. CHttpSession
useCustomStorage boolean Returns a value indicating whether to use custom session storage. CDbHttpSession
useTransparentSessionID boolean whether transparent sid support is enabled or not, defaults to false. CHttpSession

受保护属性

隐藏继承属性

属性类型描述定义在
dbConnection CDbConnection the DB connection instance CDbHttpSession

公共方法

隐藏继承方法

方法描述定义在
__call() 如果类中没有调的方法名,则调用这个方法。 CComponent
__get() 返回一个属性值、一个事件处理程序列表或一个行为名称。 CComponent
__isset() 检查一个属性是否为null。 CComponent
__set() 设置一个组件的属性值。 CComponent
__unset() 设置一个组件的属性为null。 CComponent
add() Adds a session variable. CHttpSession
asa() 返回这个名字的行为对象。 CComponent
attachBehavior() 附加一个行为到组件。 CComponent
attachBehaviors() 附加一个行为列表到组件。 CComponent
attachEventHandler() 为事件附加一个事件处理程序。 CComponent
canGetProperty() 确定属性是否可读。 CComponent
canSetProperty() 确定属性是否可写。 CComponent
clear() Removes all session variables CHttpSession
close() Ends the current session and store session data. CHttpSession
closeSession() Session close handler. CHttpSession
contains() CHttpSession
count() Returns the number of items in the session. CHttpSession
destroy() Frees all session variables and destroys all data registered to a session. CHttpSession
destroySession() Session destroy handler. CDbHttpSession
detachBehavior() 从组件中分离一个行为。 CComponent
detachBehaviors() 从组件中分离所有行为。 CComponent
detachEventHandler() 分离一个存在的事件处理程序。 CComponent
disableBehavior() 禁用一个附加行为。 CComponent
disableBehaviors() 禁用组件附加的所有行为。 CComponent
enableBehavior() 启用一个附加行为。 CComponent
enableBehaviors() 启用组件附加的所有行为。 CComponent
evaluateExpression() 计算一个PHP表达式,或根据组件上下文执行回调。 CComponent
gcSession() Session GC (garbage collection) handler. CDbHttpSession
get() Returns the session variable value with the session variable name. CHttpSession
getCookieMode() 返回how to use cookie to store session ID. Defaults to 'Allow'. CHttpSession
getCookieParams() 返回the session cookie parameters. CHttpSession
getCount() Returns the number of items in the session. CHttpSession
getEventHandlers() 返回一个事件的附加处理程序列表。 CComponent
getGCProbability() 返回the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. CHttpSession
getIsInitialized() 检查应用组件是否已经初始化。 CApplicationComponent
getIsStarted() 检查whether the session has started CHttpSession
getIterator() Returns an iterator for traversing the session variables. CHttpSession
getKeys() 返回the list of session variable names CHttpSession
getSavePath() 返回the current session save path, defaults to '/tmp'. CHttpSession
getSessionID() 返回the current session ID CHttpSession
getSessionName() 返回the current session name CHttpSession
getTimeout() 返回the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds. CHttpSession
getUseCustomStorage() Returns a value indicating whether to use custom session storage. CDbHttpSession
getUseTransparentSessionID() 返回whether transparent sid support is enabled or not, defaults to false. CHttpSession
hasEvent() 确定一个事件是否定义。 CComponent
hasEventHandler() 检查事件是否有附加的处理程序。 CComponent
hasProperty() 确定属性是否被定义。 CComponent
init() Initializes the application component. CHttpSession
itemAt() Returns the session variable value with the session variable name. CHttpSession
offsetExists() This method is required by the interface ArrayAccess. CHttpSession
offsetGet() This method is required by the interface ArrayAccess. CHttpSession
offsetSet() This method is required by the interface ArrayAccess. CHttpSession
offsetUnset() This method is required by the interface ArrayAccess. CHttpSession
open() Starts the session if it has not started yet. CHttpSession
openSession() Session open handler. CDbHttpSession
raiseEvent() 发起一个事件。 CComponent
readSession() Session read handler. CDbHttpSession
regenerateID() Updates the current session id with a newly generated one. CDbHttpSession
remove() Removes a session variable. CHttpSession
setCookieMode() 设置how to use cookie to store session ID. Valid values include 'none', 'allow' and 'only'. CHttpSession
setCookieParams() Sets the session cookie parameters. CHttpSession
setGCProbability() 设置the probability (percentage) that the gc (garbage collection) process is started on every session initialization. CHttpSession
setSavePath() 设置the current session save path CHttpSession
setSessionID() 设置the session ID for the current session CHttpSession
setSessionName() 设置the session name for the current session, must be an alphanumeric string, defaults to PHPSESSID CHttpSession
setTimeout() 设置the number of seconds after which data will be seen as 'garbage' and cleaned up CHttpSession
setUseTransparentSessionID() 设置whether transparent sid support is enabled or not. CHttpSession
toArray() CHttpSession
writeSession() Session write handler. CDbHttpSession

受保护方法

隐藏继承方法

方法描述定义在
createSessionTable() Creates the session DB table. CDbHttpSession
getDbConnection() 返回the DB connection instance CDbHttpSession

属性详细

autoCreateSessionTable 属性
public boolean $autoCreateSessionTable;

whether the session DB table should be automatically created if not exists. Defaults to true.

connectionID 属性
public string $connectionID;

the ID of a CDbConnection application component. If not set, a SQLite database will be automatically created and used. The SQLite database file is is protected/runtime/session-YiiVersion.db.

dbConnection 属性 只读

the DB connection instance

sessionTableName 属性
public string $sessionTableName;

the name of the DB table to store session content. Note, if autoCreateSessionTable is false and you want to create the DB table manually by yourself, you need to make sure the DB table is of the following structure:

(id CHAR(32) PRIMARY KEY, expire INTEGER, data TEXT)

useCustomStorage 属性 只读
public boolean getUseCustomStorage()

Returns a value indicating whether to use custom session storage. This method overrides the parent implementation and always returns true.

方法详细

createSessionTable() 方法
protected void createSessionTable(CDbConnection $db, string $tableName)
$db CDbConnection the database connection
$tableName string the name of the table to be created
源码: framework/web/CDbHttpSession.php#132 (显示)
protected function createSessionTable($db,$tableName)
{
    
$sql="
CREATE TABLE 
$tableName
(
id CHAR(32) PRIMARY KEY,
expire INTEGER,
data TEXT
)"
;
    
$db->createCommand($sql)->execute();
}

Creates the session DB table.

destroySession() 方法
public boolean destroySession(string $id)
$id string session ID
{return} boolean whether session is destroyed successfully
源码: framework/web/CDbHttpSession.php#248 (显示)
public function destroySession($id)
{
    
$sql="DELETE FROM {$this->sessionTableName} WHERE id=:id";
    
$this->getDbConnection()->createCommand($sql)->bindValue(':id',$id)->execute();
    return 
true;
}

Session destroy handler. Do not call this method directly.

gcSession() 方法
public boolean gcSession(integer $maxLifetime)
$maxLifetime integer the number of seconds after which data will be seen as 'garbage' and cleaned up.
{return} boolean whether session is GCed successfully
源码: framework/web/CDbHttpSession.php#261 (显示)
public function gcSession($maxLifetime)
{
    
$sql="DELETE FROM {$this->sessionTableName} WHERE expire<".time();
    
$this->getDbConnection()->createCommand($sql)->execute();
    return 
true;
}

Session GC (garbage collection) handler. Do not call this method directly.

getDbConnection() 方法
protected CDbConnection getDbConnection()
{return} CDbConnection the DB connection instance
源码: framework/web/CDbHttpSession.php#148 (显示)
protected function getDbConnection()
{
    if(
$this->_db!==null)
        return 
$this->_db;
    else if((
$id=$this->connectionID)!==null)
    {
        if((
$this->_db=Yii::app()->getComponent($id)) instanceof CDbConnection)
            return 
$this->_db;
        else
            throw new 
CException(Yii::t('yii','CDbHttpSession.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.',
                array(
'{id}'=>$id)));
    }
    else
    {
        
$dbFile=Yii::app()->getRuntimePath().DIRECTORY_SEPARATOR.'session-'.Yii::getVersion().'.db';
        return 
$this->_db=new CDbConnection('sqlite:'.$dbFile);
    }
}

getUseCustomStorage() 方法
public boolean getUseCustomStorage()
{return} boolean whether to use custom storage.
源码: framework/web/CDbHttpSession.php#79 (显示)
public function getUseCustomStorage()
{
    return 
true;
}

Returns a value indicating whether to use custom session storage. This method overrides the parent implementation and always returns true.

openSession() 方法
public boolean openSession(string $savePath, string $sessionName)
$savePath string session save path
$sessionName string session name
{return} boolean whether session is opened successfully
源码: framework/web/CDbHttpSession.php#174 (显示)
public function openSession($savePath,$sessionName)
{
    if(
$this->autoCreateSessionTable)
    {
        
$db=$this->getDbConnection();
        
$db->setActive(true);
        
$sql="DELETE FROM {$this->sessionTableName} WHERE expire<".time();
        try
        {
            
$db->createCommand($sql)->execute();
        }
        catch(
Exception $e)
        {
            
$this->createSessionTable($db,$this->sessionTableName);
        }
    }
    return 
true;
}

Session open handler. Do not call this method directly.

readSession() 方法
public string readSession(string $id)
$id string session ID
{return} string the session data
源码: framework/web/CDbHttpSession.php#199 (显示)
public function readSession($id)
{
    
$now=time();
    
$sql="
SELECT data FROM 
{$this->sessionTableName}
WHERE expire>
$now AND id=:id
"
;
    
$data=$this->getDbConnection()->createCommand($sql)->bindValue(':id',$id)->queryScalar();
    return 
$data===false?'':$data;
}

Session read handler. Do not call this method directly.

regenerateID() 方法 (可用自 v1.1.8)
public void regenerateID(boolean $deleteOldSession=false)
$deleteOldSession boolean Whether to delete the old associated session file or not.
源码: framework/web/CDbHttpSession.php#90 (显示)
public function regenerateID($deleteOldSession=false)
{
    
$oldID=session_id();

    
// if no session is started, there is nothing to regenerate
    
if(empty($oldID))
        return;

    
parent::regenerateID(false);
    
$newID=session_id();
    
$db=$this->getDbConnection();

    
$sql="SELECT * FROM {$this->sessionTableName} WHERE id=:id";
    
$row=$db->createCommand($sql)->bindValue(':id',$oldID)->queryRow();
    if(
$row!==false)
    {
        if(
$deleteOldSession)
        {
            
$sql="UPDATE {$this->sessionTableName} SET id=:newID WHERE id=:oldID";
            
$db->createCommand($sql)->bindValue(':newID',$newID)->bindValue(':oldID',$oldID)->execute();
        }
        else
        {
            
$row['id']=$newID;
            
$db->createCommand()->insert($this->sessionTableName$row);
        }
    }
    else
    {
        
// shouldn't reach here normally
        
$db->createCommand()->insert($this->sessionTableName, array(
            
'id'=>$newID,
            
'expire'=>time()+$this->getTimeout(),
        ));
    }
}

Updates the current session id with a newly generated one. Please refer to http://php.net/session_regenerate_id for more details.

writeSession() 方法
public boolean writeSession(string $id, string $data)
$id string session ID
$data string session data
{return} boolean whether session write is successful
源码: framework/web/CDbHttpSession.php#217 (显示)
public function writeSession($id,$data)
{
    
// exception must be caught in session write handler
    // http://us.php.net/manual/en/function.session-set-save-handler.php
    
try
    {
        
$expire=time()+$this->getTimeout();
        
$db=$this->getDbConnection();
        
$sql="SELECT id FROM {$this->sessionTableName} WHERE id=:id";
        if(
$db->createCommand($sql)->bindValue(':id',$id)->queryScalar()===false)
            
$sql="INSERT INTO {$this->sessionTableName} (id, data, expire) VALUES (:id, :data, $expire)";
        else
            
$sql="UPDATE {$this->sessionTableName} SET expire=$expire, data=:data WHERE id=:id";
        
$db->createCommand($sql)->bindValue(':id',$id)->bindValue(':data',$data)->execute();
    }
    catch(
Exception $e)
    {
        if(
YII_DEBUG)
            echo 
$e->getMessage();
        
// it is too late to log an error message here
        
return false;
    }
    return 
true;
}

Session write handler. Do not call this method directly.

Copyright © 2008-2011 by Yii Software LLC
All Rights Reserved.