SF2 : How to create a Service in 5 minutes ? Why ?

Let’s have a shortcut : a service is a set of specialized functions, packaged into a specific bundle. On a global approach, it’s like a dedicated task.

In my dev, I love service. Some of them I have written are for example in charge of:

  • SMS sending (using multiple providers, completely transparent)
  • Geocoding an address (using a cache, but also again trying multiple geocoding engines),
  • Processing emails,
  • Generating documents,

Let’s start

  1. Let’s create a new bundle (called AB3/ServiceBundle).
    php app/console generate:bundle

    Usually, I use “annotation” to declare the project.

  2. Create a new controller (MainController) inĀ AB3/ServiceBundle/Controller directory with couple of methods
    namespace AB3\ServiceBundle\Controller;
    class ServiceController {
      public function funcOne() { return "funcOne"; }
      public function funcTwo() { return "funcTwo"; }
    }
    
  3. Here is the main and most important part: declare your service. By default, Symfony2 uses xml file, which I don’t like. So, let’s do it using annotation instead, which is more convenient IMO.
    In AB3\ServiceBundle\DependencyInjection, edit “AB3ServiceExtension.php” and replace

    $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
    $loader->load('services.xml');

    by

    $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
    $loader->load('services.yml');
  4. In AB3\ServiceBundle\Resources\config. Delete services.xml and create a new services.yml file instead, where we will declare the service entry points as below:
    parameters:
        my.service.class: AB3\ServiceBundle\Controller\CacheController
    
    services:
        my.service:
            class: "%gesloc.cache.class%"

    2 important notes:
    – Under parameters, we declare the class name.
    – But the real stuff is under services: there, we declare the service name (my.service) and the class it belongs to

  5. Then to consume your service from any external controller:
    public function indexAction() {
    [...]
        $this->get('my.service')->funcOne();
        $this->get('my.service')->funcTwo();
    [...]
    }

    And that’s all !!!