3

I have a service setup in symfony 2.6 by name ge_lib and it looks like below

    ge_lib:
    class: GE\RestBundle\Services\GELib
    arguments: [@session, @doctrine.orm.entity_manager, @manage_ge_proc]

inside GELib.php I have a requirement to use a function from another service manage_ge_proc

    manage_ge_proc:
    class: GE\RestBundle\Services\GEManageProcedure
    arguments: [@doctrine.orm.entity_manager, @manage_ge_native_query] 

if I try to use it this way, it is not working

$emailInv = $this->get('manage_ge_proc');
$sendStatus = $emailInv->pSendGeneralEmail(.....);

It gives error saying that unable to find any get function by that name. generally this -> $this->get('manage_ge_proc');works in any controller.But how do i use it in service?.

I tried $this->getContainer()->get('manage_ge_proc'); but it did not work.

1 Answer 1

7

This call is fetching service from DI container, which you dont have in your service

$this->get('manage_ge_proc');

It works in controller because DI container is automatically injected there.

Since you have this line in you services.yml, which tells Symfony to inject @manage_de_proc service into ge_lib constructor

arguments: [@session, @doctrine.orm.entity_manager, @manage_ge_proc]

you should be able to pick @manage_ge_proc from constructor like this:

public function __construct(
    Session $session,
    EntityManager $entityManager, 
    GEManageProcedure $manageGeProc
)
{
    //... whatever you do in your constructor
    $this->manageGeProc = $manageGeProc;
}
3
  • this is the way to do it, make sure that the service you need is injected into your other one. You COULD if you wanted to inject the container and user the container trait in order to use $this->container->get(""); but that wouldnt be the best solution here.
    – Andy
    Nov 17, 2017 at 11:43
  • @svgrafov should the constructor look like this - public function __construct(Session $session, EntityManager $emr) instead of just variable names as arguments?. If yes, then should I add class name of the service GEManageProcedure as argument?. like public function __construct(Session $session, EntityManager $emr, GEManageProcedure $manageDeProc)
    – Manojkumar
    Nov 20, 2017 at 9:36
  • Yeah, it is possible and even highly encouraged.
    – svgrafov
    Nov 20, 2017 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.