How to use doctrine in a self-service defined in symfony

0

I am developing a web system using the concept of symfony services 3.4 Said service makes queries with dql de doctrine, these work correctly if the use of another controller. However, when I want to use them in the defined service, I get the following error:

Call to a member function has() on null

The service is defined in service.yml file as

gestionar_turnos:
    class: ComensalesBundle\Controller\GestionTurnoController

The method I'm running is the following

/**
* @Route("/turnos",name="turnos")     * 
*/
public function mostrarPanel()
{
    //return $this->render('Panel turnos/panelTurnos.html.twig');

     $servicio = $this->get('gestionar_turnos');
     $sedes = $servicio->obtenerSedes();
    return $this->render('Panel turnos/panelTurnos.html.twig',
            array('sedes' => $sedes,
                 )
            );        
}

I guess it must be a problem defining the service, possibly need some additional argument. On the other hand, is it correct to call the service as

$servicio = $this->get('gestionar_turnos');

First of all, I thank you for the good predisposition and all help is welcome. I am learning symfony and the stackoverflow community has helped me a lot. Greetings and good Saturday!

    
asked by Cristian Budzicz 23.09.2018 в 01:58
source

1 answer

0

I'll tell you how you can solve it if it's useful for other members of the community. Modify the definition of my service to the following form:

    gestionar_turnos:
    class: ComensalesBundle\Controller\GestorTurnoController
    arguments: ["@doctrine.orm.entity_manager"]
    public: true

The important thing is the inclusion of the argument parameter that is required to access Doctrine in the service that we define. On the other hand, I read that it is necessary that it be public from version 3.x of symfony.

Also, I had to include a private attribute and a constructor in my service

   class GestorTurnoController extends Controller{
protected $entityManager;

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

public function obtenerSedes()
{
    $qb = $this->entityManager->createQueryBuilder();
    $qb->select('s.id,s.nombreSede')
       ->from('ComensalesBundle:Sede','s')
       ->orderBy('s.nombreSede','ASC')
    ;
    return $qb->getQuery()->getArrayResult();
}

Finally, I call it from the function in which I need it in the following way:

$this->container->get('gestionar_turnos')->obtenerSedes();
    
answered by 02.10.2018 / 00:03
source