Skip to content

Instantly share code, notes, and snippets.

@felipyamorim
Created June 1, 2020 16:28
Show Gist options
  • Select an option

  • Save felipyamorim/e80489648fbde3c1ad27867f26caa646 to your computer and use it in GitHub Desktop.

Select an option

Save felipyamorim/e80489648fbde3c1ad27867f26caa646 to your computer and use it in GitHub Desktop.
CreatedByTrait behavior tracks your records inserts and is able to set de user who created the record.
<?php
namespace App\EventSubscriber;
use App\Entity\User;
use App\Entity\Traits\CreatedByTrait;
use App\Entity\Traits\UpdatedByTrait;
use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\Security\Core\Security;
class CreatedBySubscriber implements EventSubscriber
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function getSubscribedEvents()
{
return [
Events::prePersist,
Events::preUpdate
];
}
public function prePersist(LifecycleEventArgs $args){
/** @var CreatedByTrait $entity */
$entity = $args->getObject();
/** @var User $user */
$user = $this->security->getUser();
$exists = in_array(
CreatedByTrait::class,
class_uses($entity)
);
if( ! $exists){
return;
}
if(! $user){
return;
}
$entity->setCreatedBy($user);
}
}
<?php
/**
* Created by PhpStorm.
* User: felipyamorim
* Date: 1/12/19
* Time: 2:13 AM
*/
namespace App\Entity\Traits;
use App\Entity\User;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
trait CreatedByTrait
{
/**
* @var User $createdBy
*
* @ORM\ManyToOne(targetEntity="App\Entity\User")
* @ORM\JoinColumn(nullable=false)
*/
private $createdBy;
/**
* Get createdBy
*
* @return User
*/
public function getCreatedBy()
{
return $this->createdBy;
}
/**
* Set createdBy
*
* @param UserInterface $createdBy
*
* @return self
*/
public function setCreatedBy($createdBy)
{
$this->createdBy = $createdBy;
return $this;
}
}
services:
App\EventSubscriber\CreatedBySubscriber:
tags:
- { name: doctrine.event_subscriber, connection: default }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment