Symfony2 Use Doctrine in Service Container

user1075510 picture user1075510 · Dec 1, 2011 · Viewed 92.1k times · Source

How do I use Doctrine in a service container?

The Code just causes an error message "Fatal error: Call to undefined method ...::get()".

<?php

namespace ...\Service;

use Doctrine\ORM\EntityManager;
use ...\Entity\Header;

class dsdsf
{ 
    protected $em;

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

    public function create()
    {
        $id = 10;
        $em = $this->get('doctrine')->getEntityManager();
        $em->getRepository('...')->find($id);
    }
}

services.yml

service:
    site:
        class: ...\Service\Site

Answer

Elnur Abdurrakhimov picture Elnur Abdurrakhimov · Dec 1, 2011

According to your code, you already have an EntityManager injected. You don't need to call $em = $this->get('doctrine')->getEntityManager() — just use $this->em.

If you don't inject an EntityManager already, read this.

UPDATE:

You need to make the container inject an EntityManager into your service. Here's an example of doing it in config.yml:

services:
    your.service:
        class: YourVendor\YourBundle\Service\YourService
        arguments: [ @doctrine.orm.entity_manager ]

I prefer to define bundles' services in their own services.yml files, but that's a bit more advanced, so using config.yml is good enough to get started.