Friday, May 3, 2019

Laravel-like Timestamps With Symfony & Doctrine

I have enjoying my development time with Laravel a lot and a quite helping feature is Laravel keeping track of Model creation and update timestamps automatically when using its Eloquent ORM. Once after every indefinite days, I decide to do my next thing with Symfony. It was, is and will always be my favorite PHP framework!

After a lot of Laravel programming previously, I have been feeling sick of setting created_at and updated_at timestamps manually in each of my actions. So I figured myself a quick, re-usable way out to do it elegantly and move logic out of the actions.

It can be achieved by creating a trait in file Timestamps.php in src/Entity folder of your Symfony applications with below contents:

Then import and use the Timestamps trait in your Entity class as follows:

If you use (Doctrine) migrations for your database upgrades, you may add required created_at and updated_at columns as shown below to your table:

Hope it might help you too as it did to me!