Yii state behavior ¶
This extension is designed to simplify the implementation of the design pattern state.
Requirements ¶
Tested under Yii 1.1.6.
Installation ¶
Just unzip into the extensions directory. (I recommend to unpack it into the folder yii-state)
Usage ¶
The following example is the use of state behavior in an Account class.
class Account extends CActiveRecord
{
...
public function behaviors()
{
return array(
'state'=>array(
'class' => 'ext.yii-state.EStateBehavior', //alias for the class
//'prefix' => 'Account', //optional
'attr' => 'status', //attribute name that stores the current status
'initial' => 'active', // name of the initial status
'transitions' => array( // available states and what transactions are allowed
'active' => 'inactive,blocked',
'inactive' => 'active',
'blocked' => 'active',
),
),
);
}
}
You can implement an abstract class to specify all the methods that must exist in the state classes.
abstract class AccountStatus extends EStateStatus
{
abstract public function canLogin();
}
The name of the state classes must begin with the same name as the class model. Optionally you can change this prefix in the settings.
Importantly, the methods onExit and onEntry should return true in order to state change is performed correctly.
class AccountInactive extends AccountStatus
{
public function canLogin()
{
return false;
}
public function onExit($event)
{
// do something with $event->data
return true;
}
}
class AccountActive extends AccountStatus
{
public function canLogin()
{
return true;
}
public function onEntry($event)
{
// do something
return parent::onEntry($event);
}
}
class AccountBlocked extends AccountStatus
{
public function canLogin()
{
return false;
}
}
To invoke the methods implemented by the state just do:
$account = new Account(); //created in the active state
$account->canLogin(); //return true
$account->changeTo('blocked'); // change the state to blocked
$account->canLogin(); // return false
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.