Doctrine - Add default time stamp to entity like NOW()
Ok I found the solution:
- https://doctrine-orm.readthedocs.org/en/latest/reference/php-mapping.html?highlight=callback
- http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#lifecycle-events
The prePersist
option is what I'm doing.
Make sure you define in the annotations
<?php
/** @Entity
* @HasLifecycleCallbacks
*/
class User
and here is the function example they offer
/**
* @PrePersist
*/
public function doStuffOnPrePersist()
{
$this->createdAt = date('Y-m-d H:i:s');
}
And if you're using ORM like I am
<?php
/** @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class User
and here is the function example they offer
/**
* @ORM\PrePersist
*/
public function doStuffOnPrePersist()
{
$this->createdAt = date('Y-m-d H:i:s');
}
In my experience it is best to put everything in your Entities and not try to force your database to bypass the ORM.
<?php
namespace Phill\PaffordBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Stack
* @ORM\Table()
*/
class Stack
{
/**
* @var integer
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
*/
private $startDate;
public function __construct()
{
$this->startDate = new \DateTime();
}
}