How can I get the current user into my entity class?


Mike

I'm developing my first Symfony 4 application and migrating from Symfony 2+ and symfony 3+.

Right now I'm developing a backend where all my entity classes have addedBy()and updatedBy()methods where I need to log the currently logged in admin.

I want something like an event listener without having to set those methods in all controllers.

How do i do this?

Ivey

First, to simplify things and help you get going, I'll create an interface that this user tracking entity needs to follow:

interface UserTracking
{
    public function addedBy(UserInterface $user);
    public function updatedby(UserInterface $user);
    public function getAddedBy(): ?UserInterface;
    public function getUpdatedBy(): ?UserInterface;
}

Then you can create a Doctrine event listener and inject the Securitycomponent into it:

class UserDataListener 
{
    protected $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function prePersist(LifecycleEventArgs $event): void
    {
        $entity =  $event->getObject();
        $user   = $this->security->getUser();

        // only do stuff if $entity cares about user data and we have a logged in user
        if ( ! $entity instanceof UserTracking || null === $user ) {
            return;
        }

        $this->setUserData($entity, $user);
    }

    private function preUpdate(LifecycleEventArgs $event) {
        $this->prePersist($event);
    } 

    private function setUserData(UserTracking $entity, UserInterface $user)
    {

        if (null === $entity->getAddedBy()) {
            $entity->addedBy($user);
        }

        $entity->updatedBy($user);
    }
}    

You need to mark the listener appropriately to fire on prePersistand preUpdate:

services:
  user_data_listener:
    class: App\Infrastructure\Doctrine\Listener\UserDataListener
    tags:
      - { name: doctrine.event_listener, event: prePersist }
      - { name: doctrine.event_listener, event: preUpdate }

While the above should work, I believe that using Doctrine events this way is generally not a good idea , since you are coupling your domain logic with Doctrine and hiding your changes under a layer of magic, which is not useful for other development Personnel may not be immediately apparent. use your application.

I take it createdByas a constructor parameter and set updateByit explicitly if needed . It's only one line of code at a time, but you get clarity, expressiveness, and a simpler system with fewer moving parts.

class FooEntity
{    
    private $addedBy;
    private $updatedBy;
    public function __construct(UserInterface $user)
    {
        $this->addedBy = $user;
    }

    public function updatedBy(UserInterface $user)
    {
        $this->updatedBy = $user;
    }
}

This gives a better representation of what's going on with the domain, and future coders in your app don't have to dig through which extensions you might have installed and enabled or what events are being fired.

Related


How can I get the current user into my entity class?

Mike I'm developing my first Symfony 4 application and migrating from Symfony 2+ and symfony 3+. Right now I'm developing a backend where all my entity classes have addedBy()and updatedBy()methods where I need to log the currently logged in admin. I want somet

How can I get the current user into my entity class?

Mike I'm developing my first Symfony 4 application and migrating from Symfony 2+ and symfony 3+. Right now I'm developing a backend where all my entity classes have addedBy()and updatedBy()methods where I need to log the currently logged in admin. I want somet

How can I get the current user into my entity class?

Mike I'm developing my first Symfony 4 application and migrating from Symfony 2+ and symfony 3+. Right now I'm developing a backend where all my entity classes have addedBy()and updatedBy()methods where I need to log the currently logged in admin. I want somet

How can I get my current custom user in Spring Security?

Osama Ehadri I am using Spring Security for authentication. I created a custom user from extension and then used it Userin my customServiceDetails (implementation of UserDetailsService) , I want to be able to get that custom user, so I tried this: public class

How can I get the current instance in the class?

Johnny Cruise I don't know how to get the current instance in the class. class Basic(object): def __init__(self, val): self.val = val def current_ins(self): ??? Is there any way to get the current instance valin python ? thanks. Avina

How can I get the current instance in the class?

Johnny Cruise I don't know how to get the current instance in the class. class Basic(object): def __init__(self, val): self.val = val def current_ins(self): ??? Is there any way to get the current instance valin python ? thanks. Avina

How can I get the current instance in the class?

Johnny Cruise I don't know how to get the current instance in the class. class Basic(object): def __init__(self, val): self.val = val def current_ins(self): ??? Is there any way to get the current instance valin python ? thanks. Avina

How can I get the current instance in the class?

Johnny Cruise I don't know how to get the current instance in the class. class Basic(object): def __init__(self, val): self.val = val def current_ins(self): ??? Is there any way to get the current instance valin python ? thanks. Avina

How can I get my code to provide my current location?

Victoria Katima I'm trying to get my code to zoom in and give me my exact location after I open the map activity, but instead I get a map showing a map of Africa. I've written some code I got from online tutorials, but none of them successfully provide what I

How can I get my code to provide my current location?

Victoria Katima I'm trying to get my code to zoom in and give me my exact location after I open the map activity, but instead I get a map showing a map of Africa. I've written some code I got from online tutorials, but none of them successfully provide what I

How can I provide @current_user in my view?

Blankman In my application controller I include a module like: require 'current_user' class ApplicationController < ActionController::Base include CurrentUser end So if the token cookie is set, it will look up the user. It seems to me that I am doing this

How can I get the current user ID without hardcoding it?

Niam Flannery Laravel user ID hardcoded I currently have the id hardcoded, but I want to extract it from the id of the currently logged in user. Fixture 1212 If you are using Laravel authentication, you can try this.Auth::id();

How can I get the current active table in my script?

craft apprentice I am using the data in Google Apps Script with the following code: function getCurrentRow() { var currentRow = SpreadsheetApp.getActiveSheet().getActiveSelection().getRowIndex(); return currentRow; } However, when I use a diff

How can i get the class from the current div

Coyas I have 4 divs, this is li#click and I want to get the class of this id. I am trying to get the class from the current div but it is undefined. I use "this" to get the class only on the clicked div as there are more divs with the same functionality I use

How can I get the class's parent class in my metaclass?

Dennis I have the following script : #!/usr/bin/python3 class MyMeta(type): def __new__(mcs, name, bases, dct): print(name + " " + str(bases)) return super(MyMeta, mcs).__new__(mcs, name, bases, dct) class A(metaclass=MyMeta): def fo

How can I get the class's parent class in my metaclass?

Dennis I have the following script : #!/usr/bin/python3 class MyMeta(type): def __new__(mcs, name, bases, dct): print(name + " " + str(bases)) return super(MyMeta, mcs).__new__(mcs, name, bases, dct) class A(metaclass=MyMeta): def fo

How can I call my method from a class with user input?

dog 1 I am trying to call my method from my class by asking the user for input, and use the input to call the method. I think my best attempt is this: class Possibilities: def change_password(self): do_change_password() def do_change_password():

How can I get the class name that is calling my method?

username I want to write my own logger. Here is my logger admin: public static class LoggerManager { public static void Error(string name) { } } I am calling a Error(string name);method like this: public class Foo { public void Test() {

How can I get the class name that is calling my method?

username I want to write my own logger. Here is my logger admin: public static class LoggerManager { public static void Error(string name) { } } I am calling a Error(string name);method like this: public class Foo { public void Test() {

How can I get the execution time and add it to my class?

Nikitit I have practiced writing this simple to-do list. class Task: def __init__(self, task_name): self.task_name = [task_name, "[ ]"] def finish(self): self.task_name[1] = "[x]" class ToDoList: def __init__(self, name):

How can I get the class name that is calling my method?

username I want to write my own logger. Here is my logger admin: public static class LoggerManager { public static void Error(string name) { } } I am calling a Error(string name);method like this: public class Foo { public void Test() {