我正在尝试将一个大的service.yaml拆分为几个较小的文件。我在原产地service.yaml中
服务:
_defaults:
autowire: true
autoconfigure: true
public: false
App\Domain\Country\Infrastructure\Repository\CountryRepository:
public: true
class: App\Domain\Country\Infrastructure\Repository\CountryRepository
factory: ["@doctrine.orm.default_entity_manager", getRepository]
arguments: [App\Domain\Country\Entity\Country]
然后我在开始服务中添加了导入。yam
imports:
- {resource: services/repositories.yaml}
repositories.yaml
services:
_defaults:
autowire: true
autoconfigure: true
public: true
App\Domain\Country\Infrastructure\Repository\CountryRepository:
factory: ["@doctrine.orm.default_entity_manager", getRepository]
arguments: [App\Domain\Country\Entity\Country]
那之后我开始出现错误
Cannot autowire service "App\Domain\Country\Infrastructure\Repository\Count
ryRepository": argument "$class" of method "Doctrine\ORM\EntityRepository::
__construct()" references class "Doctrine\ORM\Mapping\ClassMetadata" but no
such service exists.
那里怎么了?
答案 0 :(得分:0)
改为使用命名参数:
repositories.yaml
services:
App\Domain\Country\Infrastructure\Repository\CountryRepository:
factory: ["@doctrine.orm.default_entity_manager", getRepository]
arguments:
$class: '@App\Domain\Country\Entity\Country'
答案 1 :(得分:0)
出于自动装配的目的,您无需定义存储库。
services.yaml:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
实体\国家:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\CountryRepository")
*/
class Country
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
}
存储库\ CountryRepository:
<?php
namespace App\Repository;
use App\Entity\Country;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* @method Country|null find($id, $lockMode = null, $lockVersion = null)
* @method Country|null findOneBy(array $criteria, array $orderBy = null)
* @method Country[] findAll()
* @method Country[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class CountryRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Country::class);
}
}
最后,您的服务:
<?php
namespace App\Service;
use App\Repository\CountryRepository;
class ExampleService
{
/**
* @var CountryRepository
*/
private $repository;
/**
* @param CountryRepository $repository
*/
public function __construct(CountryRepository $repository)
{
$this->repository = $repository;
}
}
自动装配将看到您已将CountryRepository
注入到ExampleService
构造函数中,并处理其余的事情。