1

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      
titeuf
  • 55
  • 2
  • 7

2 Answers2

1

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

Community
  • 1
  • 1
Paweł Mikołajczuk
  • 3,692
  • 25
  • 32
1

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;
    }
Tomas Votruba
  • 23,240
  • 9
  • 79
  • 115
  • 1
    Thanks a bunch, Tomáš. Exactly what I was looking for. – Denis St-Michel Jan 12 '18 at 02:16
  • Thanks for feedback. I'm glad it works :) In that case, you might find this one useful too: https://www.tomasvotruba.cz/blog/2018/01/08/clean-and-decoupled-controllers-commands-and-event-subscribers-once-and-for-all-with-delegator-pattern/ – Tomas Votruba Jan 12 '18 at 12:00