Reputation: 1256
I have the following controller in a Symfony 2.7 application:
namespace MyCompany\AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PdfPrevewController extends Controller
{
public function __construct()
{
//TODO: Inject the em instead of extending controller.
// (An error resulted when attempting to do that.)
$this->em = $this->get('doctrine.orm.default_entity_manager');
}
/**
* @Route("/admin/pdf-preview/by-document-id/{id}", name="pdf_preview_by_document_id")
*/
public function createPdfPreviewAction($id = 0)
{
die('Started.');
}
}
And when I bring up the controller in a browser, I get the following message:
Error: Call to a member function get() on null
... which I don't really understand, since extending the controller class normally gives access to the container. What am I missing here?
====
Update: I also tried defining my controller as a service and setting the container there:
app.controller.pdf_preview:
class: Exozet\AppBundle\Controller\PdfPreviewController
calls:
- [setContainer, ['@service_container']]
... with no luck. The same error message still shows up.
Upvotes: 1
Views: 3023
Reputation: 2270
$this->em = $this->get('doctrine.orm.default_entity_manager');
isn't available in constructor yet ... instead use dependency injection to set your entitymanager (clean approach)
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
or call the service in another function later (when all services are already set up)
Upvotes: 4