Blameable

Blameable

Stores who created, last changed and deleted an entity.

Entity

use Doctrine\ORM\Mapping as ORM;
use Ufo\DoctrineBehaviors\Contract\Entity\BlameableInterface;
use Ufo\DoctrineBehaviors\Model\Blameable\BlameableTrait;

#[ORM\Entity]
class Category implements BlameableInterface
{
    use BlameableTrait;

    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;
}

Mapping

Depends on the doctrine_behaviors_blameable_user_entity parameter:

Parameter Fields createdBy, updatedBy, deletedBy
not set (null) string columns, nullable
user entity class ManyToOne to that entity (columns createdBy_id etc., ON DELETE SET NULL)
# config/services.yaml
parameters:
    doctrine_behaviors_blameable_user_entity: App\Entity\User

A field already mapped in the entity is left alone.

How it works

The user is returned by UserProviderInterface (see Configuration). If it is null (no token, a console command), values are not changed.

Event What happens
prePersist createdBy and updatedBy, if empty
preUpdate updatedBy
preRemove deletedBy

The default UserProvider returns the user object from the token. If the doctrine_behaviors_blameable_user_entity parameter is not set, the columns are strings — in that case either set the parameter or plug in a provider that returns a string (a getUserIdentifier() example is in Configuration).

Usage

$category = new Category();
$entityManager->persist($category);
$entityManager->flush();

$category->getCreatedBy(); // App\Entity\User or a string — depending on the mapping
$category->getUpdatedBy();
$category->getDeletedBy(); // null