1

My doctrine entity has a datetime property called updated. This should get the current time everytime (changed) values of the object are written to the DB. I know how to do this in MySql, but I'm looking for a doctrine/symfony solution.

Is there a way to

  1. hook into something before an INSERT/UPDATE of an instance is sent to the DB.
  2. update the updated property to the current time and make sure it's written to the DB without triggering a second UPDATE statement.
BetaRide
  • 16,207
  • 29
  • 99
  • 177

2 Answers2

5

See the Timestampable behavior of DoctrineExtensions. There is StofDoctrineExtensionsBundle to intergrate it into Symfony.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
1

You don't need any extensions, just use Lifecycle Callbacks. Basically, mark your entity that it has event callbacks configured with the HasLifecycleCallbacks annotation:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * ...
 */
class MyEntityClass {
...

And then mark instance methods to be run on specific events occuring, e.g. to set updated:

...
class MyEntityClass {
...
    /**
     * @ORM\PreUpdate
     */
    public function onPreUpdate() {
        $this->updated = new \DateTime();
    }
...
Tom Imrei
  • 1,514
  • 12
  • 16