Symfony Doctrine Audit
PHP
A Symfony bundle that records every change Doctrine ORM flushes for the entities you mark as auditable: inserts, updates with old and new values, deletes. It writes them to a database, a file or a service of your own.
composer require precision-soft/symfony-doctrine-auditSymfony Doctrine Audit is a Symfony bundle that records every change Doctrine ORM flushes for the entities you mark as auditable. It captures inserts, updates with their old and new values, deletes and owning ManyToMany changes. They are written to one or more storages: a dedicated audit database, a JSONL file, or a service of your own.
It is for Symfony applications that need an audit trail of who changed what and when, without writing that bookkeeping into every service. It requires PHP 8.2 or newer, Symfony 7 or 8, Doctrine ORM 3 and Doctrine DBAL 4.2 or newer. Symfony 8 needs PHP 8.4.
Installation
composer require precision-soft/symfony-doctrine-auditRegister the bundle in config/bundles.php if it is not auto-discovered:
return [
PrecisionSoft\Doctrine\Audit\PrecisionSoftDoctrineAuditBundle::class => ['all' => true],
];Quick start
Mark an entity with #[Auditable] and exclude individual fields with #[Ignore]. Both attributes are inherited from a parent entity or a mapped superclass, and the nearest declaration wins, so #[Auditable(false)] on a child opts it out.
use PrecisionSoft\Doctrine\Audit\Attribute\Auditable;
use PrecisionSoft\Doctrine\Audit\Attribute\Ignore;
#[Auditable(true)]
#[ORM\Entity]
#[ORM\Table(name: 'product')]
class Product
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
protected ?int $id = null;
#[ORM\Column(name: 'price_in_cents', type: 'integer')]
protected int $priceInCents = 0;
#[Ignore]
#[ORM\Column(name: 'supplier_terms', type: 'string', length: 64)]
protected string $supplierTerms = '';
}Configure a storage and an auditor that watches the source entity manager:
precision_soft_doctrine_audit:
storages:
doctrine_one:
type: doctrine
entity_manager: audit_em_one
config:
transaction_table_name: 'audit_transaction'
auditors:
doctrine:
entity_manager: source_em_one
storages:
- doctrine_one
transaction_provider: Acme\Shared\Service\AuditTransactionProviderService
ignored_fields:
- created
- modifiedThe transaction provider supplies the username stored with each flush:
use PrecisionSoft\Doctrine\Audit\Contract\TransactionProviderInterface;
use PrecisionSoft\Doctrine\Audit\Dto\Storage\TransactionDto;
final class AuditTransactionProviderService implements TransactionProviderInterface
{
public function getTransaction(): TransactionDto
{
$username = '~';
return new TransactionDto($username);
}
}For each pair of auditor and doctrine storage the bundle registers precision-soft:doctrine:audit:schema:create:<auditor-name>:<storage-name> and a matching schema:update command. Both commands preview the SQL by default. Review it before adding --force to execute it. Use schema:create --force to initialise an empty audit database and schema:update to inspect later changes. After a successful creation, an update against unchanged mappings produces no SQL.
How it works
The bundle hooks into Doctrine's onFlush and postFlush events:
- During the flush, the auditor inspects the Unit of Work and collects inserts, updates and deletes; for updates it records the full change set.
- The changes are wrapped in a
StorageDtoand dispatched to every configured storage. Storages can run synchronously or asynchronously: list a subset undersynchronous_storages, for example a custom storage that publishes the DTO to a queue while a consumer writes it to the doctrine storage. - All changes of one flush are grouped under one transaction record with the username and a timestamp.
- Owning
ManyToManychanges are grouped by association, with deterministically orderedaddedandremovedidentifier lists. Doctrine storage writes them to the transaction table'scollection_changesJSON column, JSONL storage undercollections.
Storage types are doctrine (a dedicated audit database), file (JSONL appended under an exclusive flock()) and custom (a service implementing StorageInterface).
Limitations
- Bulk DQL or DBAL
UPDATEandDELETEbypass the Unit of Work and produce no audit rows. - Inverse-side and
OneToManycollections are not recorded independently; Doctrine persists them through the owning side. - The audit database must not be the source database: audit tables carry the same names as the entity tables they mirror.
- Every audited entity needs a primary key, and its identifier fields cannot be ignored.
transaction_id_column_typemust be an integer type:integer,bigintorsmallint.
Reading and purging the file storage
Every file storage registers a FileAuditReader as precision_soft_doctrine_audit.storage.<storage-name>.reader. With exactly one file storage, AuditReaderInterface and AuditPurgerInterface autowire onto it:
use PrecisionSoft\Doctrine\Audit\Contract\AuditReaderInterface;
use PrecisionSoft\Doctrine\Audit\Dto\Query\AuditQuery;
use PrecisionSoft\Doctrine\Audit\Dto\Operation;
$page = $this->auditReader->read(new AuditQuery(
entityClass: Order::class,
identity: ['id' => 42],
operation: Operation::Update,
limit: 50,
));
$nextCursor = $page->getNextCursor();Retention goes through PurgeRequest. It is a dry run by default, and it removes whole transactions only, at most batchSize per call. Start with the dry run, and set dryRun: false only when you mean to delete:
use PrecisionSoft\Doctrine\Audit\Dto\Query\PurgeRequest;
$preview = $auditPurger->purge(new PurgeRequest(new DateTimeImmutable('-1 year'), batchSize: 500));
/* this one deletes */
$result = $auditPurger->purge(new PurgeRequest(new DateTimeImmutable('-1 year'), batchSize: 500, dryRun: false));
$result->hasMore();The same operations are available as precision-soft:doctrine:audit:read:<auditor-name>:<storage-name> and precision-soft:doctrine:audit:purge:<auditor-name>:<storage-name>. The reader's payload is marked @experimental: the method signatures are stable, the shape of the returned records is not yet covered by the backward compatibility promise.
Documentation
- README: full configuration reference, performance notes, upgrade notes and exception context.
- CHANGELOG: release history.
- Example application: a runnable product catalogue audited into a second database and a JSONL file.