Reputation: 55
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
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:
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.
]);
}
}
# app/config/services.yml
services:
_defaults:
autowire: true
Project\ManagmentBundle\:
resource: ../../src/ManagmentBundle
<?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
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