从实体获取包名称

时间:2012-03-01 15:58:37

标签: symfony

如何从实体中获取捆绑包的名称?

是否有任何功能或服务可以获得此功能?

$artist = new Artist();

$bundleName = artist->getBundleName();

echo  $bundleName 
  

myCompanyArtistBundle

2 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,但不知道它是否是一个好的解决方案:

<?php
    $rootEntityName = "company\myNamespace\Entity\user";

    $bundles = $context->get('kernel')->getBundles();
    $bundleName = '';

    foreach($bundles as $type=>$bundle){
        $className = get_class($bundle);

        $entityClass = substr($rootEntityName,0,strpos($rootEntityName,'\\Entity\\'));

        if(strpos($className,$entityClass)=== FALSE){
            echo get_class($bundle).'<br>';
            echo $type.'<br>';
        }else{
            $bundleName = $type;
        }
    }
    echo $bundleName;

答案 1 :(得分:0)

我更喜欢这个解决方案:

/**
 * Get the bundle name from an Entity namespace
 *
 * @return string
 * @author lenybernard
 **/
protected static function getBundleNameFromEntity($entityNamespace, $bundles)
{
    $dataBaseNamespace = substr($entityNamespace, 0, strpos($entityNamespace, '\\Entity\\'));
    foreach ($bundles as $type => $bundle) {
        $bundleRefClass = new \ReflectionClass($bundle);
        if ($bundleRefClass->getNamespaceName() === $dataBaseNamespace) {
            return $type;
        }
    }
}

Nota bene:$bundles变量是在kernel服务上调用getBundles()方法的结果。