CStatePersister

Package system.base
Inheritance class CStatePersister » CApplicationComponent » CComponent
Implements IApplicationComponent, IStatePersister
Since 1.0
Source Code framework/base/CStatePersister.php
CStatePersister implements a file-based persistent data storage.

It can be used to keep data available through multiple requests and sessions.

By default, CStatePersister stores data in a file named 'state.bin' that is located under the application runtime path. You may change the location by setting the stateFile property.

To retrieve the data from CStatePersister, call load(). To save the data, call save().

Comparison among state persister, session and cache is as follows:
  • session: data persisting within a single user session.
  • state persister: data persisting through all requests/sessions (e.g. hit counter).
  • cache: volatile and fast storage. It may be used as storage medium for session or state persister.


Since server resource is often limited, be cautious if you plan to use CStatePersister to store large amount of data. You should also consider using database-based persister to improve the throughput.

CStatePersister is a core application component used to store global application state. It may be accessed via CApplication::getStatePersister().

Public Properties

Property Type Description Defined By
behaviors array the behaviors that should be attached to this component. CApplicationComponent
cacheID string the ID of the cache application component that is used to cache the state values. CStatePersister
isInitialized boolean Checks if this application component has been initialized. CApplicationComponent
stateFile string the file path storing the state data. CStatePersister

Public Methods

Method Description Defined By
__call() Calls the named method which is not a class method. CComponent
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getIsInitialized() Checks if this application component has been initialized. CApplicationComponent
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
init() Initializes the component. CStatePersister
load() Loads state data from persistent storage. CStatePersister
raiseEvent() Raises an event. CComponent
save() Saves application state in persistent storage. CStatePersister

Protected Methods

Method Description Defined By
getContent() Loads content from file using a shared lock to avoid data corruption when reading CStatePersister

Property Details

cacheID property

public string $cacheID;

the ID of the cache application component that is used to cache the state values. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching state values.

stateFile property

public string $stateFile;

the file path storing the state data. Make sure the directory containing the file exists and is writable by the Web server process. If using relative path, also make sure the path is correct.

Method Details

getContent() method (available since v1.1.17)

protected bool|string getContent(string $filename)
$filename string file name
{return} bool|string file contents
Source Code: framework/base/CStatePersister.php#112 (show)
protected function getContent($filename)
{
    
$file=@fopen($filename,"r");
    if(
$file && flock($file,LOCK_SH))
    {
        
$contents=@file_get_contents($filename);
        
flock($file,LOCK_UN);
        
fclose($file);
        return 
$contents;
    }
    return 
false;
}

Loads content from file using a shared lock to avoid data corruption when reading the file while it is being written by save()

init() method

public void init()
Source Code: framework/base/CStatePersister.php#61 (show)
public function init()
{
    
parent::init();
    if(
$this->stateFile===null)
        
$this->stateFile=Yii::app()->getRuntimePath().DIRECTORY_SEPARATOR.'state.bin';
    
$dir=dirname($this->stateFile);
    if(!
is_dir($dir) || !is_writable($dir))
        throw new 
CException(Yii::t('yii','Unable to create application state file "{file}". Make sure the directory containing the file exists and is writable by the Web server process.',
            array(
'{file}'=>$this->stateFile)));
}

Initializes the component. This method overrides the parent implementation by making sure stateFile contains valid value.

load() method

public mixed load()
{return} mixed state data. Null if no state data available.
Source Code: framework/base/CStatePersister.php#76 (show)
public function load()
{
    
$stateFile=$this->stateFile;
    if(
$this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
    {
        
$cacheKey='Yii.CStatePersister.'.$stateFile;
        if((
$value=$cache->get($cacheKey))!==false)
            return 
unserialize($value);
        else
        {
            if((
$content=$this->getContent($stateFile))!==false)
            {
                
$unserialized_content=unserialize($content);
                
// If it can't be unserialized, don't cache it:
                
if ($unserialized_content!==false || $content==""
                    
$cache->set($cacheKey,$content,0,new CFileCacheDependency($stateFile));
                return 
$unserialized_content;
            }
            else
                return 
null;
        }
    }
    elseif((
$content=$this->getContent($stateFile))!==false)
        return 
unserialize($content);
    else
        return 
null;
}

Loads state data from persistent storage.

save() method

public void save(mixed $state)
$state mixed state data (must be serializable).
Source Code: framework/base/CStatePersister.php#129 (show)
public function save($state)
{
    
file_put_contents($this->stateFile,serialize($state),LOCK_EX);
}

Saves application state in persistent storage.

© 2008–2017 by Yii Software LLC
Licensed under the three clause BSD license.
http://www.yiiframework.com/doc/api/1.1/CStatePersister