English 中文(简体)
如何利用实体内部的翻译服务?
原标题:How to use the translator service inside an Entity?

请允许我说,我有一个<条码>。 用户 实体:

$user = new User(007);
echo $user->getName(); // display Bond
echo $user->getGender(); // display "Male";
echo $user->getDesignation() // display "Monsieur Bond" or "Mister Bond"

具备这一职能:

public function getDesignation() {
  if ($this->getGender() ==  Male ) return "Monsieur ".$this->getName();
  else return "Madame ".$this->getName();
}

我如何利用该实体内的翻译部门翻译“Monsieur”和“Madame”?

翻译部门似乎只应在主计长内部使用,但我认为,在这种情况下,在本实体内使用翻译服务是适当的。

最佳回答

笔译部门与你一样是“服务”,你可以在任何类别(即把服务定义为服务并使用依赖性注射器集装箱)内使用服务。 因此,你几乎可以在你想要的地方使用翻译。

但是,。 不应有这种责任。 在最坏的情况下,如果你真的想将事情翻译到实体内,你可以采用一套方法,即向实体发送翻译。

$entity->setTranslator($translator);

但我也建议你设立一个在实体之外处理该问题的班级,即使用tw模板。

{{ entity.property|trans }}).
问题回答

You shouldn t and in general it is not possible. According to the Single Responsibility Principle the entity have already their purpose, which is representing data on a database. Moreover the translation is a matter of representation, so it is unlikely that you want to address such a problem in the entity layer (unless you want to provide entities translated in different languages, which totally a different problem and shouldn t even be solved using the translator).

Rethink to your logic and try something different for this. Are you sure that you don t want to do this translation on the view layer? That would be the best thing probably. Otherwise (if your logic really need to have translation at a model level) you could create a wrapper class for entities and a factory to generate this "wrapped entities"; in that factory you could inject the translator service.

我遇到了类似的问题,最后找到了这一解决办法。 这不是对你的问题的直接答案,因为我也知道,一个实体不应像笔译员那样从事任何工作。 因此,你应当离开辞职的职能。 相反,在发言层次上,例如,你翻译了法国的指定。

<div>{% trans %}{{ entity.designation }}{% endtrans %} {{ entity.name }}</div>

以及你的信息。

Monsieur: Mr.
Madame: Mrs.

问题是老的,但我决定增加一个答案,以拯救某人的时间。

Symfony has nice solution from version 5.2: Translatable Objects (similar to spackmat s solution)

https://symfony.com/blog/new-in-symfony-5-2-translatable-objects

use SymfonyComponentTranslationTranslatableMessage;
public function getDesignation(): TranslatableMessage {
    if ($this->getGender() ==  Male ) {
        $translationKey =  man_designation ;
    } else {
        $translationKey =  woman_designation ;
    }
   return new TranslatableMessage($translationKey, [ %name%  => $this->getName()]);
}

然后,在两条模板中,你可以这样做:

{{ user.designation | trans }}

过去几年来,我曾数次处理这个问题,而且总是找到了良好的工作。 我的<代码>getIdentificationName() 在整个项目中大量使用的方法(如一个明晰的) )必须翻译数据层所用的一些关键词,因此没有进行合理的工作。

我今天的解决办法是:<条码>传输目标和相应的助手服务。 <代码>TranslateObject是一个含有翻译钥匙和一系列地籍的便携物体,也可互换。 允许多层次翻译的物体(如getIdentificationName TranslateObject(),在其中一个地点内称为另一个相关物体的物体:

namespace AppUtils;

class TranslateObject
{
    /** @var string */
    protected $transKey;
    /** @var array */
    protected $placeholders;

    public function __construct(string $transKey, array $placeholders = [])
    {
        $this->transKey = $transKey;
        $this->placeholders = self::normalizePlaceholders($placeholders);
    }

    public static function normalizePlaceholders(array $placeholders): array
    {
        foreach ($placeholders as $key => &$placeholder) {
            if (substr($key, 0, 1) !==  %  || substr($key, -1, 1) !==  % ) {
                throw new InvalidArgumentException( The $placeholder attribute must only contain keys in format "%placeholder%". );
            }
            if ($placeholder instanceof TranslateObject) {
                continue;
            }
            if (is_scalar($placeholder)) {
                $placeholder = [ value  => $placeholder];
            }
            if (!isset($placeholder[ value ]) || !is_scalar($placeholder[ value ])) {
                throw new InvalidArgumentException( $placeholders[ %placeholder% ][ value ] must be present and a scalar value. );
            }
            if (!isset($placeholder[ translate ])) {
                $placeholder[ translate ] = false;
            }
            if (!is_bool($placeholder[ translate ])) {
                throw new InvalidArgumentException( $placeholders[ %placeholder% ][ translate ] must be a boolean. );
            }
        }
        return $placeholders;
    }

    public function getTransKey(): string
    {
        return $this->transKey;
    }

    public function getPlaceholders(): array
    {
        return $this->placeholders;
    }
}

The helper looks like this and does the work:

namespace AppServices;

use AppUtilsTranslateObject;
use SymfonyContractsTranslationTranslatorInterface;

class TranslateObjectHelper
{
    /** @var TranslatorInterface */
    protected $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    public function trans(TranslateObject $translateObject): string
    {
        $placeholders = $translateObject->getPlaceholders();
        foreach ($placeholders as $key => &$placeholder) {
            if ($placeholder instanceof TranslateObject) {
                $placeholder = $this->trans($placeholder);
            }
            elseif (true === $placeholder[ translate ]) {
                $placeholder = $this->translator->trans($placeholder[ value ]);
            }
            else {
                $placeholder = $placeholder[ value ];
            }
        }

        return $this->translator->trans($translateObject->getTransKey(), $placeholders);
    }
}

然后在实体内有<条码>认证NametranslateObject()的方法,可回归<条码>。 目标

/**
 * Get an identifying name as a TranslateObject (for use with TranslateObjectHelper)
 */
public function getIdentifyingNameTranslateObject(): TranslateObject
{
    return new TranslateObject( my.whatever.translation.key , [
         %placeholder1%  => $this->myEntityProperty1,
         %placeholderWithANeedOfTranslation%  => [
             value  =>  my.whatever.translation.values.  . $this->myPropertyWithANeedOfTranslation,
             translate  => true,
        ],
         %placeholderWithCascadingTranslationNeeds%  => $this->getRelatedEntity()->getIdentifyingNameTranslateObject(),
    ]);
}

当我需要归还这种翻译财产时,我需要查阅我的注入式<编码>TranslateObjectHelper服务,并使用其trans()方法,如控制器或任何其他服务:

$this->translateObjectHelper->trans($myObject->getIdentifyingNameTranslateObject());

随后,我创建了一个tw子过滤器,作为简单的助手。

namespace AppTwig;

use AppServicesTranslateObjectHelper;
use AppUtilsTranslateObject;

class TranslateObjectExtension extends Twig_Extension
{
    /** @var TranslateObjectHelper */
    protected $translateObjectHelper;

    public function __construct(TranslateObjectHelper $translateObjectHelper)
    {
        $this->translateObjectHelper = $translateObjectHelper;
    }

    public function getFilters()
    {
        return array(
            new Twig_SimpleFilter( translateObject , [$this,  translateObject ]),
        );
    }

    /**
    * sends a TranslateObject through a the translateObjectHelper->trans() method
    */
    public function translateObject(TranslateObject $translateObject): string
    {
        return $this->translateObjectHelper->trans($translateObject);
    }

    public function getName(): string
    {
        return  translate_object_twig_extension ;
    }
}

因此,在特维格,我可以这样说:

{{ myObject.getIdentifyingNameTranslateObject()|translateObject }}

最后,我“说明”需要找到所有关于这些实体的<条码>、(或<代码>.在Twig中识别Name,将其替换为<条码>,代之以<条码>,<>trans(>>>>>>>(或<条码>>>>在Twig中译





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签