phpsymfonysymfony-2.6

how to use a service inside another service in symfony 2.6


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.


Solution

  • 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;
    }