rfgmig
Last Updated: May 02, 2019
·
1.021K
· zoltanradics

Symfony2 - Services #2

If you have read my previous protip about Symfony2: Services #1 you noted that in some case you will need inject dependencies for your service. In this chapter i will show you how you can do that.

Let's register a service with inject dependecies:

example_service:
  class: ExampleVendor\SomeBundle\Service\ExampleService
  arguments: [ @doctrine, @service_container ]

In this case we injected doctrine if you gonna do anything with your database, and also inject service container if you gonna do something like templating or use another service or use security context.

Let's see how it looks like in the service class:

namespace ExampleVendor\SomeBundle\Service;

// This needs becouse of doctrine
use Symfony\Bridge\Doctrine\RegistryInterface as RegistryInterface;

class ExampleService
{

  private $doctrine; 
  private $serviceContainer;

  public function __construct(RegistryInterface $doctrine, $serviceContainer) 
    {
        $this->doctrine = $doctrine;
        $this->serviceContainer = $serviceContainer;
  }

}

public function someExampleMethod() 
{

   # Get the current user
   $user = $this->serviceContainer->get('security.context')->getToken()->getUser();

   # Get entities from a repository
   $entities = $this->doctrine->getRepository('SomeBundle:Something')->findAll();

   # User templating for some reason (for eg. send a HTML mail out)
   $html = $this->serviceContainer->get('templating')->renderResponse('SomeBundle:Default:file.html.twig');

)

As you can see i added 3 simple examples to demonstrate how you can use dependencies in Symfony2 services. If you have any further questions do not hesitate to ask on @zoltanradics at Twitter or below in comment.