Reputation: 1081
I would like to inject a repository into a service. My first step was to define the repository as service, like:
<service id="app.repository.user" class="AppBundle\Entity\UserRepository">
<factory class="doctrine" method="getRepository" />
<argument>AppBundle:User</argument>
</service>
In second step i inject the defined repository service
<service id="app.registration_handler" class="AppBundle\Utils\RegistrationHandler">
<argument type="service" id="security.password_encoder" />
<argument type="service" id="app.repository.user" />
</service>
But i get this error message:
Attempted to load class "doctrine" from the global namespace.
Did you forget a "use" statement?
I remember that this works in previous versions, have someone the same issue and a hint for me?
I'm using Symfony 3.01
Update: I solve my issue. I made the mistake to define a class instead of a service, now it workts.
<factory service="doctrine" method="getRepository" />
Upvotes: 4
Views: 2474
Reputation: 1359
Another idea is to use the "expression language" into service configuration
<service id="app.registration_handler" class="AppBundle\Utils\RegistrationHandler">
<argument type="service" id="security.password_encoder" />
<argument type="expression">service('doctrine').getRepository('AppBundle:User')</argument>
</service>
Upvotes: -1
Reputation: 24280
Since 2017 and Symfony 3.3+ there is quite easy way to do this.
Check my post How to use Repository with Doctrine as Service in Symfony for more general description.
To your code - all you need to do is create own repository as service.
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
class UserRepository
{
private $repository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(User::class);
}
// add desired methods here
public function findAll()
{
return $this->repository->findAll();
}
}
# app/config/services.yml
services:
_defaults:
autowire: true
AppBundle\:
resource: ../../src/AppBundle
<?php
namespace AppBundle\Controller;
use AppBundle\Repository\UserRepository;
class MyController
{
/**
* @var UserRepository
*/
private $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = userRepository
}
}
Upvotes: 2