A
A
Alexander Vladimirovich2019-06-11 12:08:11
symfony
Alexander Vladimirovich, 2019-06-11 12:08:11

Why is injecting a service into an entity considered bad practice?

Hey!
Why is injecting a service into an entity considered bad practice?
For example UserPasswordEncoderInterface in User->setPassword
or NotBlank validator in User setUsername

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris Korobkov, 2019-06-11
@BorisKorobkov

It is more correct to say not "bad practice", but "violates SOLID".
"Service in essence" violates the Single Responsibility Principle (SRP) by combining in one object both the representation of the object itself and some external logic.
It doesn't mean it's "bad" or "good"! There are different (sometimes mutually exclusive) approaches, it is not necessary to run into strict adherence to them all. Here is an example where this can greatly complicate development: https://habr.com/ru/post/153225/
UserPasswordEncoderInterface and NotBlank are not services, but validators. They refer to the internal logic of the object, not only do not violate the SRP, but they must be in this object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question