如何使用Knp Labs可翻译原则行为访问翻译后的属性

sma*_*erx 5 doctrine symfony

我正在使用可翻译的学说,并且我有一个具有可翻译属性的实体。看起来像这样。

class Scaleitem
{
    /**
     * Must be defined for translating this entity
     */
    use ORMBehaviors\Translatable\Translatable;

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
}
Run Code Online (Sandbox Code Playgroud)

而且我有一个文件ScaleitemTranslation:

class ScaleitemTranslation
{
    use ORMBehaviors\Translatable\Translation;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $text;


    /**
     * Set text
     *
     * @param string $text
     * @return ScaleitemTranslation
     */
    public function setText($text)
    {
        $this->text = $text;

        return $this;
    }

    /**
     * Get text
     *
     * @return string 
     */
    public function getText()
    {
        return $this->text;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想从控制器访问文本:

$item = $em->getRepository('AppMyBundle:Scaleitem')->find(1);
dump($item->getText());
Run Code Online (Sandbox Code Playgroud)

这行不通。有人暗示我的问题吗?

gp_*_*ver 3

如可翻译文档所示中所示,您可以使用以下方式访问翻译:

  • $item->translate('en')->getName();当您想要特定语言时
  • __call或在实体中添加方法Scaleitem(而不是在翻译的实体上):

    /**
     * @param $method
     * @param $args
     *
     * @return mixed
     */
    public function __call($method, $args)
    {
        if (!method_exists(self::getTranslationEntityClass(), $method)) {
            $method = 'get' . ucfirst($method);
        }
    
        return $this->proxyCurrentLocaleTranslation($method, $args);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    然后使用$item->getName();并始终检索当前语言环境中的任何“属性”。