Loggable

← Loggable

Ashterix

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

en/docs/doctrine/doctrine-behaviors/loggable.md new file +54 āˆ’0

1 + # Loggable
2 +
3 + Writes messages about entity creation, changes and removal to a PSR-3 logger.
4 +
5 + ## Entity
6 +
7 + ```php
8 + use Doctrine\ORM\Mapping as ORM;
9 + use Ufo\DoctrineBehaviors\Contract\Entity\LoggableInterface;
10 + use Ufo\DoctrineBehaviors\Model\Loggable\LoggableTrait;
11 +
12 + #[ORM\Entity]
13 + class Category implements LoggableInterface
14 + {
15 + use LoggableTrait;
16 +
17 + #[ORM\Id, ORM\GeneratedValue, ORM\Column]
18 + private ?int $id = null;
19 +
20 + #[ORM\Column]
21 + private string $title = '';
22 +
23 + public function getId(): ?int
24 + {
25 + return $this->id;
26 + }
27 + }
28 + ```
29 +
30 + The trait calls `getId()`, so the entity must have that method. The behavior adds no columns.
31 +
32 + ## How it works
33 +
34 + | Event | Message (`info` level) |
35 + | --- | --- |
36 + | `postPersist` | `App\Entity\Category #1 created` and the field changes |
37 + | `postUpdate` | a line per changed field: `App\Entity\Category #1 : property "title" changed from "Old" to "New"` |
38 + | `preRemove` | `App\Entity\Category #1 removed` |
39 +
40 + Arrays in the message are replaced with `an array`, `DateTime` values are formatted as `Y-m-d H:i:s.u`.
41 +
42 + The messages are built by `getCreateLogMessage()`, `getUpdateLogMessage(array $changeSets)` and `getRemoveLogMessage()` — override them in the entity to change the text.
43 +
44 + ## Logger
45 +
46 + `LoggableEventSubscriber` gets `Psr\Log\LoggerInterface` by autowiring — in an application with MonologBundle it is the `app` channel. Another channel or service:
47 +
48 + ```yaml
49 + # config/services.yaml
50 + services:
51 + Ufo\DoctrineBehaviors\EventSubscriber\LoggableEventSubscriber:
52 + arguments:
53 + $logger: '@monolog.logger.doctrine'
54 + ```