Timestampable

← Timestampable

Ashterix

docs: Doctrine section with Doctrine Behaviors and Doctrine Helper (uk + en)

en/docs/doctrine/doctrine-behaviors/timestampable.md new file +52 āˆ’0

1 + # Timestampable
2 +
3 + Stores when an entity was created and last changed.
4 +
5 + ## Entity
6 +
7 + ```php
8 + use Doctrine\ORM\Mapping as ORM;
9 + use Ufo\DoctrineBehaviors\Contract\Entity\TimestampableInterface;
10 + use Ufo\DoctrineBehaviors\Model\Timestampable\TimestampableTrait;
11 +
12 + #[ORM\Entity]
13 + class Category implements TimestampableInterface
14 + {
15 + use TimestampableTrait;
16 +
17 + #[ORM\Id, ORM\GeneratedValue, ORM\Column]
18 + private ?int $id = null;
19 + }
20 + ```
21 +
22 + ## How it works
23 +
24 + * On `loadClassMetadata` the bundle maps `createdAt` and `updatedAt` (nullable, type from the `doctrine_behaviors_timestampable_date_field_type` parameter, `datetime` by default) and adds the `updateTimestamps()` lifecycle callback on `prePersist` and `preUpdate`. The `#[ORM\HasLifecycleCallbacks]` attribute is not needed.
25 + * `updateTimestamps()` sets `createdAt` if it is still `null` and always updates `updatedAt`. The time has microseconds and uses the `date_default_timezone_get()` time zone.
26 + * Doctrine calls `preUpdate` only for entities with changed fields — a `flush()` without changes leaves `updatedAt` alone.
27 + * `#[ORM\MappedSuperclass]` is skipped; the columns go to the child entities.
28 +
29 + ## Usage
30 +
31 + ```php
32 + $category = new Category();
33 + $entityManager->persist($category);
34 + $entityManager->flush();
35 +
36 + $category->getCreatedAt(); // DateTime
37 + $category->getUpdatedAt(); // DateTime
38 + ```
39 +
40 + `setCreatedAt()` and `setUpdatedAt()` let you set values manually; a `createdAt` set this way is not overwritten on save.
41 +
42 + ## Configuration
43 +
44 + ```yaml
45 + # config/services.yaml
46 + parameters:
47 + doctrine_behaviors_timestampable_date_field_type: datetimetz
48 + ```
49 +
50 + :::warning
51 + The trait writes `DateTime`, so only mutable types fit — `datetime` and `datetimetz`. The `*_immutable` types expect `DateTimeImmutable` and are not compatible.
52 + :::