Understanding Symfony2 Services

I am very new to Symfony 2, and I will move on to advanced topics such as services . When should an object be a service?

For example, say you have a facade object to call the REST service. This class requires a username and password. Would it be proper to model this class as a global service? Even if it is used only in part of the entire project?

# app/config/config.yml parameters: my_proxy.username: username my_proxy.password: password services: my_proxy: class: Acme\TestBundle\MyProxy arguments: [%my_proxy.username%, %my_proxy.password%] 
+6
source share
2 answers

Definition taken from the Symfony2 glossary :

A service is a general term for any PHP object that performs a specific task. A service is typically used โ€œglobally,โ€ for example, a database connection object or an object that delivers email messages. In Symfony2, services are often configured and retrieved from a service container. It is said that an application that has many services disabled has a service-oriented architecture.

I think your example is an ideal candidate for a service.

You do not want to copy the construction code to all the places where you need the API client. It is better to delegate this task to the dependency injection container.

Thus, it is easier to maintain (since the construction takes place in one place and is configured).

It is also more flexible, as you can easily change the class of the API client without affecting the code that uses it (as long as it implements the same interface).

I do not think that there is a golden rule. But basically all classes that implement the task are good service candidates. Organizations, on the other hand, are not like most data owners.

I always recommend a series of Fabien related articles: http://fabien.potencier.org/article/11/what-is-dependency-injection

+13
source

Yes, because it will save you part of the configuration. You will not receive a username and password and assign it to the constructor every time you need this class.

+1
source

Source: https://habr.com/ru/post/901883/


All Articles