0

OK, one may argue that there shouldn't be business logic in entity. But sometimes there is a good reason. For example when getting roles for a user, one may force a role to be returned by default from within getter method, for example as explained here.

Anyway, my question is in many documentation pages it is either done in the function which creates/updates user or with doctrine listener. For example as mentioned here.

Doing it manually every time is extra work, meanwhile using doctrine listener seems inefficient for something which will be used rarely.

So, I was wondering, why not encode the password within setPlainPassword() function in entity? always one needs to encode the password after calling this method anyway.

Next part of the question is how to access the encoder from inside the User entity?

Thanks!

Evren Yurtesen
  • 2,267
  • 1
  • 22
  • 40
  • Why would you introduce that coupling between `User` entity and `UserPasswordEncoderInterface`? Also in how many places are you setting the password in your application? Doing that in the controller responsible for the registration is the best place because there you can inject `UserPasswordEncoderInterface` (which is way better) so you can encode the `plainPassword` value and store it in the password field. Note that `plainPassword` is just used for form and validation and never persisted. – dlondero Jan 23 '18 at 08:15
  • if you use Symfony <= 3.4, try to see https://github.com/FriendsOfSymfony/FOSUserBundle – Weenesta - Mathieu Dormeval Jan 23 '18 at 08:25
  • The role_user was stored in the entity, the domain logic granting roles to a specified is not store in the entity. It's the same for the password, your entity store the result of the domain logic generating it. I don't see any extra works, how many time do you encode a new password to a user manually? it's just a service call. (I'm a "Domain logic is not meant to be in entity" guy :p) – goto Jan 23 '18 at 08:41
  • 1
    Business logic should be in entity classes, otherwise you would not need entity classes at all: https://youtu.be/rzGeNYC3oz0 – Đuro Mandinić Jan 23 '18 at 09:58
  • It may be used at password reset, user registration, update profile and more places probably if you have API etc... This is why people make it as doctrine listener even. But the simple fact is that if you have entity do it automatically, you don't have to think about it ever again if you ever need to set new password to a user. – Evren Yurtesen Jan 23 '18 at 10:06
  • @ĐuroMandinić in the video the encoder is passed as a callable argument, not coupled to the user. I meant the user shouldn't be aware of the encoder algorythm used. the exemple of the video: `changePassword($pass; callable $hasher) { $this->password = $hash($pass)}`. – goto Jan 23 '18 at 14:47

0 Answers0