How do I use Unix timestamps with the Doctrine Timestampable behavior? I found the following code snippet here, but I’d rather not manually add this everywhere:
$this->actAs('Timestampable', array(
'created' => array('name' => 'created_at',
'type' => 'integer',
'format' => 'U',
'disabled' => false,
'options' => array()),
'updated' => array('name' => 'updated_at',
'type' => 'integer',
'format' => 'U',
'disabled' => false,
'options' => array())));
This is a question that might get an answer easier than what I first thought, actually…
Let’s begin by what you have now :
Doctrine_RecordTest, for my example(s).Testmodel, you want to use theTimestampableBehaviour, but with UNIX timestamps, and notdatetimevalues(I can understand that : less risk to forget one line somewhere and at wrong data in DB)
A solution to this problem would be to not use the default
Timestampablebehaviour that comes with Doctrine, but another one, that you will define.Which means, in your model, you will have something like this at the bottom of
setTableDefinitionmethod :(I suppose this could go in the
setUpmethod too, btw — maybe it would be it’s real place, actually)What we now have to do is define that
MyTimestampablebehaviour, so it does what we want.As Doctrine’s
Doctrine_Template_Timestampablealready does the job quite well (except for the format, of course), we will inherit from it ; hopefully, it’ll mean less code to write ๐So, we declare our behaviour class like this :
Now, let’s have a look at what
Doctrine_Template_Timestampableactually does, in Doctrine’s code source :created_atandupdated_atfields)Let’s have a look at the source of this one ; we notice this part :
This means if the type of the two
created_atandupdated_atfields is notdatenortimestamp,Doctrine_Template_Listener_Timestampablewill automatically use an UNIX timestamp — how convenient !As you don’t want to define the
typeto use for those fields in every one of your models, we will modify ourMyTimestampableclass.Remember, we said it was extending
Doctrine_Template_Timestampable, which was responsible of the configuration of the behaviour…So, we override that configuration, using a
typeother thandateandtimestamp:We said earlier on that our model was acting as
MyTimestampable, and notTimestampable… So, now, let’s see the result ๐If we consider this model class for
Test:Which maps to the following MySQL table :
We can create two rows in the table this way :
If we check the values in the DB, we’ll get something like this :
So, we are OK for the creation of rows, it seems ๐
And now, let’s fetch and update the second row :
And, back to the DB, we now get this :
The
updated_atfield has been updated, and thecreated_atfield has not changed ; which seems OK too ๐So, to make things short, fit in a couple of bullet points, and summarize quite a bit :
MyTimestampable, and not the defaultTimestampableI will let you do some more intensive tests, but I hope this helps !
Have fun ๐