4

I have a regular class in my Symfony2 project:

    class RangeColumn extends Column{
        //...
    }

Now inside this class is a render function, in which I'd like to use Twig or the Translation Service of Symfony2 to render a specific template. How do I access this services in a proper way?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
worenga
  • 5,776
  • 2
  • 28
  • 50

2 Answers2

10

Code example:

<?php

class MyRegularClass
{
    private $translator;

    public function __construct(Translator $translator)
    {
        $this->translator = $translator;
    }

    public function myFunction()
    {
        $this->translator->trans('sentence_to_translate');
    }
}

And if you want your class to become a service: In your services.yml file located in your bundle,

parameters:
    my_regular_class.class: Vendor\MyBundle\Classes\MyRegularClass

services:
    mybundle.classes.my_regular_class:
        class: %my_regular_class.class%
        arguments: [@translator]

For more details, see the chapter about the Symfony2 Service Container

Nanocom
  • 3,696
  • 4
  • 31
  • 46
  • 2
    Dependency Injection tag is `@translator.default` by Symfony 2.6, the `@translator` tag refers to LoggingTranslator now. – Lashae Dec 01 '14 at 15:35
9

Use dependency injection. It's a really simple concept.

You should simply pass (inject) needed services to your class.

If dependencies are obligatory pass them in a constructor. If they're optional use setters.

You might go further and delegate construction of your class to the dependency injection container (make a service out of it).

Services are no different from your "regular" class. It's just that their construction is delegated to the container.

crmpicco
  • 16,605
  • 26
  • 134
  • 210
Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125