smartcoderx
smartcoderx

Reputation: 1081

How to inject repository into a service

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

Answers (2)

Arno
Arno

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

Tomas Votruba
Tomas Votruba

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.

1. Create own repository without direct dependency on Doctrine

<?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();
    }
}

2. Add config registration with PSR-4 based autoregistration

# app/config/services.yml
services:
    _defaults:
        autowire: true

    AppBundle\:
        resource: ../../src/AppBundle

3. Injecting repository to any service or controller is now EASY

<?php

namespace AppBundle\Controller;

use AppBundle\Repository\UserRepository;    

class MyController
{
    /**
     * @var UserRepository
     */
    private $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = userRepository
    }
}

Upvotes: 2

Related Questions