Answer the question
In order to leave comments, you need to log in
How to use services in Symphony4 correctly?
How to properly access services in Symphony4? What is correct, from a stylistic point of view?
For example, you need to get data about an authorized user. Here you can go 2 ways
1. Pass through method parameters
public function index(TokenStorageInterface $token) {
$user = $token->getToken()->getUser();
}
public function index() {
$user = $this->get('security.token_storage')->getToken()->getUser();
}
Answer the question
In order to leave comments, you need to log in
You need to use the first option. In it, we implement the dependency injection pattern, while in the second case, the pattern (rather, even anti) is the service locator. The service locator hides class/method dependencies and creates redundant code cohesion that now depends on that same container. It becomes inconvenient to mock dependencies for testing.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question