The Timestampable behavior will automatically add a created_at and updated_at column and automatically set the values when a record is inserted and updated.
Since it is common to want to know the date a post is made lets expand our BlogPost model and add the Timestampable behavior to automatically set these dates for us.
// models/BlogPost.php
class BlogPost extends Doctrine_Record
{
// ...
public function setUp()
{
$this->actAs('Timestampable');
}
}
Here is the same example in YAML format. You can read more about YAML in the YAML Schema Files chapter:
---
# schema.yml
# ...
BlogPost:
actAs:
# ...
Timestampable:
# ...
If you are only interested in using only one of the columns, such as a created_at timestamp, but not a an updated_at field, set the disabled to true for either of the fields as in the example below.
---
BlogPost:
actAs:
# ...
Timestampable:
created:
name: created_at
type: timestamp
format: Y-m-d H
updated:
disabled: true
# ...
Now look what happens when we create a new post:
$blogPost = new BlogPost();
$blogPost->title = 'Test blog post';
$blogPost->body = 'test';
$blogPost->save();
print_r($blogPost->toArray());
The above example would produce the following output:
$ php test.php
Array
(
[id] => 1
[title] => Test blog post
[body] => test
[version] => 1
[created_at] => 2009-01-21 17:54:23
[updated_at] => 2009-01-21 17:54:23
)
Look how the created_at and updated_at values were automatically set for you!
Here is a list of all the options you can use with the Timestampable behavior on the created side of the behavior:
| Name | Default | Description |
|---|---|---|
| name | created_at | The name of the column. |
| type | timestamp | The column type. |
| options | array() | Any additional options for the column. |
| format | Y-m-d H:i:s | The format of the timestamp if you don't use the timestamp column type. The date is built using PHP's date() function. |
| disabled | false | Whether or not to disable the created date. |
| expression | NOW() | Expression to use to set the column value. |
Here is a list of all the options you can use with the Timestampable behavior on the updated side of the behavior that are not possible on the created side:
| Name | Default | Description |
|---|---|---|
| onInsert | true | Whether or not to set the updated date when the record is first inserted. |