简体   繁体   English

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

[英]Extract the Namespace or Bundle Shortcut for a Symfony Entity

I have a function that needs to know the bundle shortcut name for an entity that is passed in. 我有一个函数需要知道传入实体的捆绑软件快捷方式名称。

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

I would love to have it return the bundle shortcut name of my entity: 我希望它返回我实体的捆绑软件快捷方式名称:

GutensiteCmsBundle:ViewVersion

Is this possible? 这可能吗? Does the entity manager have access to this metadata somehow? 实体管理员是否可以某种方式访问​​此元数据?

I'm aware I could pre-register the name in all my entities: 我知道我可以在所有实体中预先注册该名称:

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

Then I can do: 然后我可以做:

$entity->getBundleName();

But that's lame. 但这很la脚。

SOLUTION

Based on @Chamlee's answer, this is the function I use: 基于@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];
}

So for the following entities here are the return values: 因此,对于以下实体,这是返回值:

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


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

Try looking at this : 尝试看这个:

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

It returns you an array with all you need ;) If you make and echo of the $className you'll see the structure and I think it could fit with your problem. 它返回一个数组,其中包含您所需要的全部;)如果您对$ className进行了构造和回显,则将看到该结构,我认为它可能适合您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM