CDbHttpSession

优质
小牛编辑
127浏览
2023-12-01
所有包 | 属性 | 方法
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.

公共属性

隐藏继承属性

属性类型描述定义在
autoCreateSessionTablebooleanwhether the session DB table should be automatically created if not exists.CDbHttpSession
autoStartbooleanwhether the session should be automatically started when the session application component is initialized, defaults to true.CHttpSession
behaviorsarray这个应用组件附加的行为。 这此行为将在应用组件调用init时附加在应用组件上。 请参照CModel::behaviors如何指定此属性值。CApplicationComponent
connectionIDstringthe ID of a CDbConnection application component.CDbHttpSession
cookieModestringhow to use cookie to store session ID.CHttpSession
cookieParamsarraythe session cookie parameters.CHttpSession
countintegerReturns the number of items in the session.CHttpSession
gCProbabilityintegerthe probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.CHttpSession
isInitializedboolean检查应用组件是否已经初始化。CApplicationComponent
isStartedbooleanwhether the session has startedCHttpSession
iteratorCHttpSessionIteratorReturns an iterator for traversing the session variables.CHttpSession
keysarraythe list of session variable namesCHttpSession
savePathstringthe current session save path, defaults to '/tmp'.CHttpSession
sessionIDstringthe current session IDCHttpSession
sessionNamestringthe current session nameCHttpSession
sessionTableNamestringthe name of the DB table to store session content.CDbHttpSession
timeoutintegerthe number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.CHttpSession
useCustomStoragebooleanReturns a value indicating whether to use custom session storage.CDbHttpSession
useTransparentSessionIDbooleanwhether transparent sid support is enabled or not, defaults to false.CHttpSession

受保护属性

隐藏继承属性

属性类型描述定义在
dbConnectionCDbConnectionthe DB connection instanceCDbHttpSession

公共方法

隐藏继承方法

方法描述定义在
__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 variablesCHttpSession
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 startedCHttpSession
getIterator()Returns an iterator for traversing the session variables.CHttpSession
getKeys()返回the list of session variable namesCHttpSession
getSavePath()返回the current session save path, defaults to '/tmp'.CHttpSession
getSessionID()返回the current session IDCHttpSession
getSessionName()返回the current session nameCHttpSession
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 pathCHttpSession
setSessionID()设置the session ID for the current sessionCHttpSession
setSessionName()设置the session name for the current session, must be an alphanumeric string, defaults to PHPSESSIDCHttpSession
setTimeout()设置the number of seconds after which data will be seen as 'garbage' and cleaned upCHttpSession
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 instanceCDbHttpSession

属性详细

autoCreateSessionTable 属性 public boolean $autoCreateSessionTable;

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

参见

  • sessionTableName
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 属性 只读 protected CDbConnection getDbConnection()

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)

参见

  • autoCreateSessionTable
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)
$dbCDbConnectionthe database connection
$tableNamestringthe name of the table to be created
源码: framework/web/CDbHttpSession.php#132 (显示) protectedfunctioncreateSessionTable($db,$tableName)
{
$sql="
CREATETABLE$tableName
(
idCHAR(32)PRIMARYKEY,
expireINTEGER,
dataTEXT
)";
$db->createCommand($sql)->execute();
}

Creates the session DB table.

destroySession() 方法
public boolean destroySession(string $id)
$idstringsession ID
{return}booleanwhether session is destroyed successfully
源码: framework/web/CDbHttpSession.php#248 (显示) publicfunctiondestroySession($id)
{
$sql="DELETEFROM{$this->sessionTableName}WHEREid=:id";
$this->getDbConnection()->createCommand($sql)->bindValue(':id',$id)->execute();
returntrue;
}

Session destroy handler. Do not call this method directly.

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

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

getDbConnection() 方法
protected CDbConnection getDbConnection()
{return}CDbConnectionthe DB connection instance
源码: framework/web/CDbHttpSession.php#148 (显示) protectedfunctiongetDbConnection()
{
if($this->_db!==null)
return$this->_db;
elseif(($id=$this->connectionID)!==null)
{
if(($this->_db=Yii::app()->getComponent($id))instanceofCDbConnection)
return$this->_db;
else
thrownewCException(Yii::t('yii','CDbHttpSession.connectionID"{id}"isinvalid.PleasemakesureitreferstotheIDofaCDbConnectionapplicationcomponent.',
array('{id}'=>$id)));
}
else
{
$dbFile=Yii::app()->getRuntimePath().DIRECTORY_SEPARATOR.'session-'.Yii::getVersion().'.db';
return$this->_db=newCDbConnection('sqlite:'.$dbFile);
}
}
getUseCustomStorage() 方法
public boolean getUseCustomStorage()
{return}booleanwhether to use custom storage.
源码: framework/web/CDbHttpSession.php#79 (显示) publicfunctiongetUseCustomStorage()
{
returntrue;
}

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)
$savePathstringsession save path
$sessionNamestringsession name
{return}booleanwhether session is opened successfully
源码: framework/web/CDbHttpSession.php#174 (显示) publicfunctionopenSession($savePath,$sessionName)
{
if($this->autoCreateSessionTable)
{
$db=$this->getDbConnection();
$db->setActive(true);
$sql="DELETEFROM{$this->sessionTableName}WHEREexpire<".time();
try
{
$db->createCommand($sql)->execute();
}
catch(Exception$e)
{
$this->createSessionTable($db,$this->sessionTableName);
}
}
returntrue;
}

Session open handler. Do not call this method directly.

readSession() 方法
public string readSession(string $id)
$idstringsession ID
{return}stringthe session data
源码: framework/web/CDbHttpSession.php#199 (显示) publicfunctionreadSession($id)
{
$now=time();
$sql="
SELECTdataFROM{$this->sessionTableName}
WHEREexpire>$nowANDid=: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)
$deleteOldSessionbooleanWhether to delete the old associated session file or not.
源码: framework/web/CDbHttpSession.php#90 (显示) publicfunctionregenerateID($deleteOldSession=false)
{
$oldID=session_id();

//ifnosessionisstarted,thereisnothingtoregenerate
if(empty($oldID))
return;

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

$sql="SELECT*FROM{$this->sessionTableName}WHEREid=:id";
$row=$db->createCommand($sql)->bindValue(':id',$oldID)->queryRow();
if($row!==false)
{
if($deleteOldSession)
{
$sql="UPDATE{$this->sessionTableName}SETid=:newIDWHEREid=:oldID";
$db->createCommand($sql)->bindValue(':newID',$newID)->bindValue(':oldID',$oldID)->execute();
}
else
{
$row['id']=$newID;
$db->createCommand()->insert($this->sessionTableName,$row);
}
}
else
{
//shouldn'treachherenormally
$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)
$idstringsession ID
$datastringsession data
{return}booleanwhether session write is successful
源码: framework/web/CDbHttpSession.php#217 (显示) publicfunctionwriteSession($id,$data)
{
//exceptionmustbecaughtinsessionwritehandler
//http://us.php.net/manual/en/function.session-set-save-handler.php
try
{
$expire=time()+$this->getTimeout();
$db=$this->getDbConnection();
$sql="SELECTidFROM{$this->sessionTableName}WHEREid=:id";
if($db->createCommand($sql)->bindValue(':id',$id)->queryScalar()===false)
$sql="INSERTINTO{$this->sessionTableName}(id,data,expire)VALUES(:id,:data,$expire)";
else
$sql="UPDATE{$this->sessionTableName}SETexpire=$expire,data=:dataWHEREid=:id";
$db->createCommand($sql)->bindValue(':id',$id)->bindValue(':data',$data)->execute();
}
catch(Exception$e)
{
if(YII_DEBUG)
echo$e->getMessage();
//itistoolatetologanerrormessagehere
returnfalse;
}
returntrue;
}

Session write handler. Do not call this method directly.