JSGarcia
JSGarcia

Reputation: 566

Problems with doctrine in Symfony controller

I have an error that I can find no solution. I have a driver Symfony this:

<?php

namespace Consolidador\PanelBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DataController extends Controller
{

    public function listOfUsers()
    {
        $em = $this->getDoctrine()->getManager();
        $settings = $em->getRepository('PanelBundle:Users')->findAll();

        return $settings;

    }

}

As seen only returns a list of users using Doctrine, well when I call on any method, like this:

    $users = new DataController();
    $listOfUsers = $users->listOfUsers()

An exception appears in the DataController class that has to do with Doctrine:

Error: Call to a member function has() on a non-object

I do not understand what happens and I'm using and extending the controller so you should be able to access Doctrine without any error ... In other controllers use Doctrine without major problems.

Any solution?

Thank you very much.

Upvotes: 2

Views: 709

Answers (1)

Tomasz Madeyski
Tomasz Madeyski

Reputation: 10920

This is because the way you create instance of a class. A regular symfony controller instance is created by service container which calls setContainer method on it. Your DataController class has no knowledge about container and that's why you get an error (you can't just do new DataController()).

A quick and dirty way to solve this is just set container on your DataController instance:

$users = new DataController();
$users->setContainer($container); //you need to have container available, I don't know what context are you in
$listOfUsers = $users->listOfUsers();

A proper way to do this is to define your Controller as a service, inject Doctrine into it and get it by

$dataController = $this->container->get('your_data_controller_class');

IMPORTANT NOTE: Other thing is that Controller is meant to take Request, and return Response object, in your case you are returning an array which is not good. You should move this logic somewhere outside Controller class - something like UserManager class. Then you should define this UserManager as a service, inject Doctrine, do your logic there and return data (an array). Than in your controller you should call this service.

This way you will get cleaner code and move logic outside of controller.

Upvotes: 4

Related Questions