gpt4 book ai didi

Symfony 2.2 Doctrine ResolveTargetEntities 监听器

转载 作者:行者123 更新时间:2023-12-02 05:17:25 25 4
gpt4 key购买 nike

我正在创建一个包含关系关联的 bundle 。为了保持抽象,我想使用 Doctrine 的全新 ResolveTargetEntities 监听器。

问题是我希望监听器的设置是自动化的,这样 future 使用我的包的开发人员就不需要自己配置监听器了。

在我的包中,有一个名为 data_class 的配置参数,我想用它来设置 ResolveTargetEntities 监听器:

# app/config/config.yml
my_bundle:
City:
data_class: Acme\DemoBundle\Entity\City

如何在我的包中设置服务或配置文件以使用此参数配置监听器?像这样:

resolve_target_entities:
Dev\MyBundle\Model\City: %my_bundle.City.data_class%

编辑:

上面的配置示例是为了展示 Doctrine 应该完成什么,但是这个问题的目的是找到一种方法来自动设置 ResolveTargetEntities 监听器,使用服务,依赖注入(inject)容器,或要求最终用户在 my_bundle 命名空间下仅提供一个参数的任何其他方式:data_class

最佳答案

您可以为此使用 DependancyInjection 文件夹中的 Bundle Extension 类。有一个选项可以将自定义配置添加到另一个捆绑配置 ( http://symfony.com/doc/current/cookbook/bundles/prepend_extension.html )。下面是我执行相同操作的代码。

<?php

namespace Zveen\CmsBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class ZveenCmsExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

$container->setParameter('zveen.cmsbundle.tenant.class', $config['tenant']['class']);
$container->setParameter('zveen.cmsbundle.tenant.dql', $config['tenant']['class']);

$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}

/**
* Allow an extension to prepend the extension configurations.
*
* @param ContainerBuilder $container
*/
public function prepend(ContainerBuilder $container)
{
// get all Bundles
$bundles = $container->getParameter('kernel.bundles');
if (isset($bundles['DoctrineBundle'])) {
// Get configuration of our own bundle
$configs = $container->getExtensionConfig($this->getAlias());
$config = $this->processConfiguration(new Configuration(), $configs);

// Prepare for insertion
$forInsertion = array(
'orm' => array(
'resolve_target_entities' => array(
'Zveen\CmsBundle\Entity\TenantInterface' => $config['tenant']['class']
)
)
);
foreach ($container->getExtensions() as $name => $extension) {
switch ($name) {
case 'doctrine':
$container->prependExtensionConfig($name, $forInsertion);
break;
}
}
}
}
}

关于Symfony 2.2 Doctrine ResolveTargetEntities 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14424876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com