Detailed description of Yii Behavior
The following is a simple example of reusable database update and insertion time.
The yii Framework providesCTimestampBehaviorBehavior class. you only need to set the createAttribute and updateAttribute attributes, which correspond to the creation time and update time fields of your database table respectively. For example, when creating an article, we usually need to record the creation time, the update time when it is updated, detailed use, in your Model classBehaviorsMethodAdd the following linesYou can change createAttribute and updateAttribute to the time field corresponding to your database.:
123456789 |
Publicfunctionbehaviors () {returnarray ('ctimestampbehavior '=> array ('class' => 'zii. behaviors. CTimestampBehavior ', 'createattribute' => 'Create _ time_attribute', 'updateattribute '=> 'update _ time_attribute ',));} |
XSS security mode
In this article, we will describe a WEB-based application to avoid illegal content injection.
We need to use the htmlpurifier class in an action, which can enhance any model and indicate the attributes we want to make them XSS secure.
I wrote the following behavior:
1234567891011121314151617 |
Purifier = newCHtmlPurifier;} publicfunctionbeforeSave ($ event) {foreach ($ this-> attributesas $ attribute) {$ this-> getOwner () ->{$ attribute }=$ this-> purifier-> purify ($ this-> getOwner ()->{$ attribute });}}} |
Put this class in your application directory, such as application/behaviors/CSafeContentBehavior. php. Now you write the following in the Model behavior:
123456789101112 |
Array ('class' => 'application. behaviors. CSafeContentBehavior ', 'bubuckets' => array ('title', 'body '),),);}} |
Now we can start. Our Post model clears the title and content columns in each save operation.
After saving a record, update the order number, which is suitable for all order numbers
1234567891011121314151617181920 |
GetOwner ()-> getIsNewRecord () {if (empty ($ this-> pk) | empty ($ this-> orderNo) | empty ($ this-> prefix) {returnfalse;} $ id = $ this-> getOwner ()-> {$ this-> pk }; $ model = $ this-> getOwner ()-> findByPk ($ id); $ model-> {$ this-> orderNo} = $ this-> prefix. date ('ymmd '). str_pad ($ id, 5, '0', STR_PAD_LEFT); $ model-> save ();}}} |
Automatic module import
1234567891011121314151617181920212223242526272829303132333435 |
'Beginrequest',);}/*** Load configuration that cannot be put in config/main */publicfunctionbeginRequest () {$ modules = array (); $ model = Module:: model ()-> findAll (); // Todo-shocould be per application foreach ($ modelas $ item) {$ modules [$ item-> name] = array (); // Todo can set parameters here for each module ...} // $ modules ['video'] = array (); Yii: app ()-> setModules ($ modules) ;}}?> |
Main. php code
12 |
'Behavires' => array ('application. components. behaviors. ApplicationConfigBehavior '),; |