S
S
s0lar2018-02-25 22:45:04
symfony
s0lar, 2018-02-25 22:45:04

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();
}

2. Call through a call to the container
public function index() {
  $user = $this->get('security.token_storage')->getToken()->getUser();
}

Both methods work, but only 1 method is found in the documentation. In all examples, the call is as in 1 example. Method 2 was more actively used in early versions of the Symphony.
So the question is, how to use services more correctly, from the point of view of the Symfony way?
Personally, I like method 2, because it is more compact. But in the documentation I did not meet a single example in this style!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D3lphi, 2018-02-25
@s0lar

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 question

Ask a Question

731 491 924 answers to any question