我正在处理捆绑软件,我需要从配置参数加载学说resolve_target_entities。
This article应该是我的解决方案,事实是,使用捆绑包似乎无法加载“编译器传递类”。
这是我的捆绑包类
class PersonalBundle extends Bundle
{
public function build(ContainerBuilder $container){
parent::build($container);
$container->addCompilerPass(new ResolveTargetEntitiesPass());
}
}
这是ResolveTargetEntitiesPass类
class ResolveTargetEntitiesPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
// Gets the custom entity defined by the user (or the default one)
$customEntityClass = $container->getParameter('personal.custom_class');
// Skip the resolve_target_entities part if user has not defined a different entity
if (DefaultClassInterface::DEFAULT_ENTITY_CLASS == $customEntityClass) {
return;
}
// Throws exception if the class isn't found
if (!class_exists($customEntityClass)) {
throw new ClassNotFoundException(sprintf("Can't find class %s ", $customEntityClass));
}
// Get the doctrine ResolveTargetEntityListener
$def = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity');
// Adds the resolve_target_enitity parameter
$def->addMethodCall('addResolveTargetEntity', array(
DefaultClassInterface::DEFAULT_ENTITY_CLASS, $customEntityClass, array()
));
// This was added due this problem
// https://stackoverflow.com/a/46656413/7070573
if (version_compare(Version::VERSION, '2.5.0-DEV') < 0 && !$def->hasTag('doctrine.event_listener')) {
$def->addTag('doctrine.event_listener', array('event' => 'loadClassMetadata'));
} elseif (!$def->hasTag('doctrine.event_subscriber')) {
$def->addTag('doctrine.event_subscriber');
}
}
}
当我使用该类时,会引发此错误
类型为“ PersonalBundle \ Entity \ DefaultClass”的期望值 对于关联字段“ PersonalBundle \ Entity \ Group#$ defaultClass”,得到 改为使用“ App \ Entity \ CustomClass”。
正如我所说,似乎不加载ResolveTargetEntitiesPass ... 谢谢
答案 0 :(得分:0)
所以我解决了更改编译器传递优先级的问题。
我尝试将捆绑软件移至config/bundle.php
的顶部,然后开始工作,然后遵循https://symfony.com/blog/new-in-symfony-3-2-compiler-passes-improvements,我保留了默认类型,但增加了优先级(从0,默认为1)。
我不确定哪个服务已被“降级”,所以如果有人有想法可以欢迎。
<?php
// ...
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
class PersonalBundle extends Bundle
{
public function build(ContainerBuilder $container){
parent::build($container);
$container->addCompilerPass(new ResolveTargetEntitiesPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 1);
}
}