Gen*_*ito 0 php doctrine-orm symfony4
我正在使用Symfony 4,我有很多具有共同行为的存储库,所以我想避免重复代码。我试图通过这种方式定义父存储库类:
<?php
namespace App\Repository;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
class AppRepository extends ServiceEntityRepository {
public function __construct(RegistryInterface $registry, $entityClass) {
parent::__construct($registry, $entityClass);
}
// Common behaviour
}
Run Code Online (Sandbox Code Playgroud)
因此,我可以定义其子类,例如:
<?php
namespace App\Repository;
use App\Entity\Test;
use App\Repository\AppRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
class TestRepository extends AppRepository {
public function __construct(RegistryInterface $registry) {
parent::__construct($registry, Test::class);
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
无法自动装配服务“ App \ Repository \ AppRepository”:方法“ __construct()”的参数“ $ entityClass”必须具有类型提示,或必须被明确赋予值。
我尝试设置类似的类型提示string,object但是没有用。
有没有定义通用存储库的方法?
提前致谢
autowire的“陷阱”之一是,默认情况下,autowire会在src下查找所有类,并尝试使它们成为服务。在某些情况下,它最终会拾取诸如AppRepository之类的类,这些类不打算用作服务,然后在尝试自动装配它们时失败。
最常见的解决方案是显式排除以下类:
# config/services.yaml
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php,Repository/AppRepository.php}'
Run Code Online (Sandbox Code Playgroud)
另一个可行的方法(未经测试)是使AppRepository抽象。Autowire将忽略抽象类。存储库有些棘手,让抽象类扩展非抽象类有点不寻常。
小智 6
只需让您的 AppRepository 抽象,例如
abstract class AppRepository {}
Run Code Online (Sandbox Code Playgroud)