Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Symfony2 services

Tags:

symfony

I'm quite new to Symfony 2 and I'm moving to advanced topics like services. When should an object be a service?

For example, say that you have a facade object for making a call to a REST service. This class needs a username and password. Would it be correct modeling that class as a global service? Even if it's used only in a portion of the whole 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%]
like image 730
gremo Avatar asked Nov 19 '11 11:11

gremo


2 Answers

Definition taken from the Symfony2 glossary:

A Service is a generic term for any PHP object that performs a specific task. A service is usually used "globally", such as a database connection object or an object that delivers email messages. In Symfony2, services are often configured and retrieved from the service container. An application that has many decoupled services is said to follow a service-oriented architecture.

I think your example is a perfect candidate for a service.

You don't want to copy construction code to all places you need your API client. It's better to delegate this task to the dependency injection container.

This way it's easier to maintain (as construction happens in one place and it's configurable).

It's also more flexible as you can easily change the API client class without affecting code which uses it (as long as it implements the same interface).

I don't think there's a golden rule. But basically all classes implementing a task are good candidates for a service. Entities on the other hand are not as they're most often just data holders.

I always recommend Fabien's series of articles on the subject: http://fabien.potencier.org/article/11/what-is-dependency-injection

like image 177
Jakub Zalas Avatar answered Sep 30 '22 12:09

Jakub Zalas


Yes, because this will spare you the configuration part. You're not going to fetch the username and password and give it to the constructor each time you need this class.

like image 31
greg0ire Avatar answered Sep 30 '22 12:09

greg0ire