Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access services inside a regular class

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?

like image 511
worenga Avatar asked Dec 01 '22 00:12

worenga


2 Answers

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

like image 53
Nanocom Avatar answered Dec 04 '22 02:12

Nanocom


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.

like image 21
Jakub Zalas Avatar answered Dec 04 '22 03:12

Jakub Zalas