Symfony 3 use service within another service

0

I appeal to the knowledge of the community to resolve a doubt about the use of services, about whether it is feasible to use the functionalities of one service within another.

I have two two defined services whose nomeclature is as follows:

GestorSolicitudController
GestorTurnosController

If in the GestorTurnoController , I try to call a function declared in GestorTurnosController as follows:

$servicio = $this->container->get('gestor_solicitudes');
$solicitud = $servicio->obtenerSolicitudActual($dni);

I get the error Call to a member function get () on null Provisionally, I solved it using dependency injection, declaring an attribute in the following way:

class GestorTurnoController extends Controller
{
   protected $entityManager;
   //usamos injeccion de dependencias porque no puedo usar un servicio en otro
//to-do ver como resolverlo
protected $solicitudes;

public function __construct($entityManager)
{
    $this->entityManager = $entityManager;
    $this->solicitudes = new GestorSolicitudController($entityManager);
}

In this way, it works correctly. But I have the doubt if it is that you can not use a service within another, if it is feasible you can tell me how and if not, what is resolved with dependency injection. Thanks!

    
asked by Cristian Budzicz 10.11.2018 в 16:17
source

1 answer

0

I solved the problem with a concept that is new to me: service injection

Googleando I found the following references of symfony 2.x link link2 Where they explain the use of injection of one service within another.

In my case, modify the file services.yml in the following way:

    gestor_turnos:
    class: ComensalesBundle\Servicios\GestorTurnoController
    arguments: ["@doctrine.orm.entity_manager","@gestor_solicitudes"]
    public: true

The @gestor_solicitudes argument that refers to the other service that I am interested in was incorporated.

In the controller, modify the constructor in the following way:

class GestorTurnoController extends Controller
{
protected $entityManager;
protected $solicitudes;

//referencia de inyeccion de dependencias
public function __construct($entityManager,$gestor_solicitudes)
{
    $this->entityManager = $entityManager;
    $this->solicitudes = $gestor_solicitudes;
}

Now in the methods that I need to access a function of the injected service, I only write:

$this->solicitudes->metodoQueQuieroUsar();

I hope it serves you!

    
answered by 14.11.2018 / 02:47
source