CreatedTrait
The snippet can be accessed without any authentication.
Authored by
Thomas Flori
A trait I'm using for tflori/orm models
<?php
namespace App\Model;
use ORM\Entity;
trait CreatedTrait
{
/**
* Get a DateTime object from created
*
* @return \DateTime|null
*/
public function getCreated()
{
if (!$this instanceof Entity) {
return null;
}
$col = static::getColumnName('created');
if (!isset($this->data[$col])) {
return null;
}
return new \DateTime($this->data[$col]);
}
/**
* Set created to $dt or 'now'
*
* @param \DateTime|null $dt
* @return $this
*/
public function setCreated(\DateTime $dt = null)
{
if (!$this instanceof Entity) {
return $this;
}
$col = static::getColumnName('created');
if (isset($this->data[$col])) {
return $this;
}
$dt = $dt ?? \DateTime::createFromFormat('U.u', microtime(true))
->setTimezone(new \DateTimeZone('UTC'));
$this->data[$col] = $dt->format('Y-m-d\TH:i:s.u\Z');
return $this;
}
}
Please register or sign in to comment