Almost every model representing content should have creation and modification dates to show the content actuality, revisions, and so on. In Yii there are two good ways to automate this, which are as follows:
beforeValidate
CTimestampBehavior
behavior from ZiiWe will see how to apply these to blog posts. We will use Unix timestamps to store the date and time.
yiic webapp
as described in the official guide at the following URL:http://www.yiiframework.com/doc/guide/en/quickstart.first-app
post
as follows:DROP TABLE IF EXISTS `post`; CREATE TABLE IF NOT EXISTS `post` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `title` VARCHAR(255) NOT NULL, `text` TEXT NOT NULL, `created_on` INT(10) UNSIGNED NOT NULL, `modified_on` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`id`) );
Post
model using Gii.created_on
and modified_on
from the rules
method of the model.beforeValidate
method. Open protected/models/Post.php
and add the following method:protected function beforeValidate() { if($this->getIsNewRecord()) $this->created_on = time(); $this->modified_on = time(); return parent::beforeValidate();; }
$post = new Post(); $post->title = "test title"; $post->text = "test text"; $post->save(); echo date('r', $post->created_on);
CTimestampBehavior
. Delete the Post
model and generate it one more time by using Gii. Remove everything about created_on
and modified_on
from the rules
method of the model. Add the following method to the model:public function behaviors() { return array( 'timestamps' => array( 'class' => 'zii.behaviors.CTimestampBehavior', 'createAttribute' => 'created_on', 'updateAttribute' => 'modified_on', 'setUpdateOnCreate' => true, ), ); }
The beforeValidate
method executes just before the model validation starts. In this method, modified_on
is always filled and created_on
is filled only if the model is new, which is only when we are creating a post.
When we use the ready behavior from Zii, we specify createAttribute
and updateAttribute
to match the field names we have chosen. The setUpdateOnCreate
property triggers filling modified_on
when a record is inserted. The rest is done by the behavior
function.
In order to learn more about CTimestampBehavior
, refer to the following API page:
3.144.25.74