I want to use doctrine in my bundle. When use this in the class that extends Controller:
$em = $this->getDoctrine()->getEntityManager();
and if i want to use doctrine in other class that doesn't extend Controller . I know about this , i should define doctrine as service , and i do this:
php class :
namespace News\VillageNewsBundle\Services;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DoctrineService extends Controller
{
protected $em;
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
}
?>
service.yml
services:
doctrine:
class: News\VillageNewsBundle\Services\DoctrineService
arguments: - @doctrine.orm.default_entity_manager
config.yml
imports:
- { resource: "@NewsVillageNewsBundle/Resources/config/services.yml" }
when do up levels i encounter with this error:
ErrorException: Catchable Fatal Error: Argument 1 passed to Symfony\Bridge\Doctrine\CacheWarmer\ProxyCacheWarmer::__construct() must be an instance of Doctrine\Common\Persistence\ManagerRegistry, instance of News\VillageNewsBundle\Services\DoctrineService given, called in /var/www/Symfony/app/cache/dev/appDevDebugProjectContainer.php on line 402 and defined in /var/www/Symfony/vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/CacheWarmer/ProxyCacheWarmer.php line 34
I believe that the reason you get this error is that you define doctrine
service, which already exists. Just change the name and it should work fine:
services.yml:
services:
some_other_name:
class: News\VillageNewsBundle\Services\DoctrineService
arguments: [@doctrine.orm.default_entity_manager]
doctrine
is already a service, that's why you are getting this error.
Why do you need to wrap doctrine into another service? Doctrine already is a service. You have to declare the other class that need to use doctrine as a service, then you inject the entity manager on that service.
Let's assume you have a FooBar
class:
<?php
namespace News\VillageNewsBundle\Services;
use Doctrine\ORM\EntityManager;
class FooBar
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
}
You just declare this class as a service and pass the EntityManager
, like this:
services:
my_service:
class: News\VillageNewsBundle\Services\FooBar
arguments: ['@doctrine.orm.entity_manager']