Skip to content

Instantly share code, notes, and snippets.

@artyuum
Last active November 5, 2021 10:29
Show Gist options
  • Save artyuum/43d8604805979178887c92548629e8ba to your computer and use it in GitHub Desktop.
Save artyuum/43d8604805979178887c92548629e8ba to your computer and use it in GitHub Desktop.
Adding a timestampable feature to your entities in Symfony
services:
App\EventSubscriber\TimestampSubscriber:
tags:
- { name: 'doctrine.event_subscriber' }
<?php
namespace App\Entity\Traits;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
trait TimestampableTrait
{
/**
* @ORM\Column(type="datetime_immutable")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime_immutable", nullable=true)
*/
private $updatedAt;
public function getCreatedAt(): ?DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(?DateTimeImmutable $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?DateTimeImmutable
{
return $this->updatedAt;
}
public function setUpdatedAt(?DateTimeImmutable $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
}
<?php
namespace App\EventSubscriber;
use App\Entity\Traits\TimestampableTrait;
use DateTime;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
class TimestampSubscriber implements EventSubscriber
{
/**
* Ensures that the entity uses the "TimestampableTrait" trait.
*
* @param $entity
*/
private function supports($entity): bool
{
return in_array(TimestampableTrait::class, class_uses($entity), true);
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getObject();
if (!$this->supports($entity)) {
return;
}
// sets the createdAt value only if it hasn't been set
if ($entity->getCreatedAt() === null) {
$entity->setCreatedAt(new DateTime());
}
}
public function preUpdate(LifecycleEventArgs $args)
{
/** @var TimestampableTrait $entity */
$entity = $args->getObject();
if (!$this->supports($entity)) {
return;
}
$entity->setUpdatedAt(new DateTime());
}
public function getSubscribedEvents(): array
{
return [
Events::prePersist,
Events::preUpdate,
];
}
}
@artyuum
Copy link
Author

artyuum commented Jul 27, 2021

Usage in an entity

<?php

namespace App\Entity;

use App\Entity\Traits\TimestampableTrait;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User
{
    use TimestampableTrait;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment