Home » Php » Automatic values for updated_at, created_at in Doctrine

Automatic values for updated_at, created_at in Doctrine

Posted by: admin November 30, 2017 Leave a comment

Questions:

I want to make fields updated_at and created_at in my Doctrine entities to update automatically.

In Ruby on Rails models there are 2 fields: updated_at and created_at.

Description can be found here: http://guides.rubyonrails.org/migrations.html#migration-overview:

The timestamps macro adds two columns, created_at and updated_at. These special columns are automatically managed by Active Record if they exist.

Can I enable similar functionality in Doctrine 2?

Answers:

Yes you can for createdAt you can add $this>setCreatedAt(new \DateTime()); into __construct method, for both you can use Life Cycle Callbacks :

 /**
 *
 * @ORM\PrePersist
 * @ORM\PreUpdate
 */
public function updatedTimestamps()
{
    $this->setUpdatedAt(new \DateTime('now'));

    if ($this->getCreatedAt() == null) {
        $this->setCreatedAt(new \DateTime('now'));
    }
}

And don’t forget to add into entity class notation:

 * @ORM\HasLifecycleCallbacks

Questions:
Answers:

This is another option if you would ever want to handle them separately.

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="person")
 * @ORM\HasLifecycleCallbacks
 */
class Person
{
    ..........

    /**
     * @var datetime $created
     *
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @var datetime $updated
     * 
     * @ORM\Column(type="datetime", nullable = true)
     */
    protected $updated;


    /**
     * Gets triggered only on insert

     * @ORM\PrePersist
     */
    public function onPrePersist()
    {
        $this->created = new \DateTime("now");
    }

    /**
     * Gets triggered every time on update

     * @ORM\PreUpdate
     */
    public function onPreUpdate()
    {
        $this->updated = new \DateTime("now");
    }

    ..........
}