titeuf
titeuf

Reputation: 55

Call service into EntityRepository

how I can call a service in this EntityRepository

class CityRepository extends EntityRepository{

   public function guessCity($name){
    // ..... call service
   }
}

this is my service

namespace Project\ManagmentBundle\Services;

class FormatString {

public function replaceAccents($str)
{ 
  .....
}

services.yml

services:
project.format_string:
  class: Project\ManagmentBundle\Services\FormatString      

Upvotes: 1

Views: 3238

Answers (2)

Tomas Votruba
Tomas Votruba

Reputation: 24298

Since 2017 and Symfony 3.3+, you can do this easily with service pattern.

Passing service to repository is not bad practise, it was just so complicated that it would create really messy code, if you'd try to do so.

Check my post How to use Repository with Doctrine as Service in Symfony for more general description.

To your code:

1. Remove direct dependency on Doctrine from your Repository

namespace Project\ManagmentBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class CityRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(City::class);
    }

    public function guessCity($name)
    {
        return $this->repository->findBy([ 
            'name' => $name // improve logic with LIKE %...% etc.
        ]);
    }
}

2. Register services with autowiring

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

    Project\ManagmentBundle\:
       resource: ../../src/ManagmentBundle

3. Adding any service to repository is now easy

<?php

use Project\ManagmentBundle\Services\FormatString;

class CityRepository
{
    private $repository;

    private $formatString;

    public function __construct(EntityManagerInterface $entityManager, FormatString $formatString)
    {
        $this->repository = $entityManager->getRepository(City::class);
        $this->formatString = $formatString;
    }

Upvotes: 1

Paweł Mikołajczuk
Paweł Mikołajczuk

Reputation: 3822

You shouldn't do this. Rather you should call repository from your service.

IMO passing any container service to repository is bad practice.

But if you really need to do that, then you can register your repository as a service, and then inject other service to it. Here is nice answer for that case: https://stackoverflow.com/a/17230333/919567

Upvotes: 1

Related Questions