Monday, December 5, 2011

How to create a Service to embed business logic functions in Symfony2

Services are classes where you will write the Business Logic code or any other treatment that you want to make accessible to a controller or another service. The Logger delivered with Symfony2 is a service, like the Registry of Doctrine, which gives access to the EntityManager.

The example below shows how to create a service, to pass two services it can use as parameters.
1- We begin by defining our service in the configuration file for services of our bundle (AcmeDemoBundle) :
src/Acme/DemoBundle/Resources/config/services.xml
<?xml version="1.0" ?>
 

 
    
        
          
        
 
        
          
        
 
        
        
            
            
            
        
        
    
 

Was added a node , passed the service name in the id attribute and PHP class in class attribute.
As parameters we added 2 of type "service" : the Doctrine registry service (id = "doctrine") and logger (id = "logger").
We added one more to which we return later ...