提取Symfony实体的命名空间或包快捷方式


Extract the Namespace or Bundle Shortcut for a Symfony Entity

我有一个函数需要知道传入实体的bundle快捷方式名称。

public function doSomething($entity) {
     $bundleShortcut = SOMEFUNCTION($entity);
     // ... do other stuff and return a value ...
}

我希望它能返回我实体的bundle快捷方式名称:

GutensiteCmsBundle:ViewVersion

这可能吗?实体管理器是否以某种方式访问此元数据?

我知道我可以在我所有的实体中预先注册这个名字:

class ViewVersion {
    protected $bundleName = 'GutensiteCmsBundle:ViewVersion';
    public function getBundleName() {
        return $this->bundleName;
    }
}

然后我可以做:

$entity->getBundleName();

但这太差劲了。

解决方案

根据@Chamlee的回答,这是我使用的函数:

public function getEntityBundleShortcut($entity) {
    // wrap in EntityManager's Class Metadata function avoid problems with cached proxy classes
    $path = explode(''Entity''', $this->em->getClassMetadata(get_class($entity))->getName());
    return str_replace('''', '', $path[0]).':'.$path[1];
}

那么对于以下实体,这里是返回值:

// Entity
Gutensite'ArticleBundle'Entity'Article
// Returns
GutensiteArticleBundle:Article

// Entity
Gutensite'CmsBundle'Entity'View'ViewVersion
// Returns
GutensiteArticleBundle:View'ViewVersion

试着看看这个:

$className = explode("''", get_class($document));

它返回一个包含所有你需要的数组;)如果你做$className的echo,你会看到结构,我认为它可以满足你的问题。