yvrhlg
Last Updated: February 25, 2016
·
546
· zoltanradics

Symfony2 - Services #1

Keep your controller thin

This is a sentence what you have to keep in mind when you are using an MVC framework. The basic approach in professional development is separate code to the smallest logic blocks. For eg. if you have a function to send an email, don't place the function into the controller directly. Create and register a service for it instead and call it in the controller. You can keep your controllers skinny and your code will be more readable.

Create the service

Symfony2 services are simply plain PHP objects. Imagine that you would place your service in your bundle:

# Your file is here:
# /src/ExampleVendor/SomeBundle/Service/ExampleService.php

namespace ExampleVendor\SomeBundle\Service;

class ExampleService
{

  function __construct()
  {
    # Add some code to run when object instance created
  }

}

Register the service

Now you have done with the service itself but you have to tell the framework to use it. Edit your services.yml in your 'SomeBundle/Resources/config/services.yml

services:

  example_service: 
    class: ExampleVendor\SomeBundle\Service\ExampleService

Let me give a quick explain. 'example_service' is a reference name of the service. 'class' is to tell the framework which php class is use for your service.

Use the service

So now your service is ready to use. Let's call it in a controller:

class HelloController extends Controller
{

  public function indexAction()
  {
    $exampleService = $this->get('example_service');
  }

}

Not that fast...

In this tip i explained to create and register a service in Symfony2. However i am sure you will have dependencies of the service. For eg. when you wanna do something with your database. In my next pro tip i will explain to inject dependency to the service.