在 Symfony2 中处理字符串表示和数字代码翻译的最佳方法是什么?
假设我有这样一个实体:
<?php
class Message
{
const STATUS_NEW = 0;
const STATUS_SENT = 1;
const STATUS_DELIVERED = 2;
/**
* @var int
*/
private $status = self::STATUS_NEW;
public function getStatus()
{
return $this->status;
}
}
在前端和 SonataAdmin 后端,我不想显示数字代码,而是显示字符串。例如"new"、“已发送”和“已交付”。但我也希望能够翻译这些字符串(例如荷兰语“Nieuw”、“Verzonden”和“Afgeleverd”)。
所以有两个转换步骤:首先从数字代码到字符串或翻译键,然后到本地化字符串。
我在哪里以及如何最好地进行这些转换?在我自己的 Controller / View 的前端和基于支持的 SonataAdmin 中?
最佳答案
如果我是你,我会在我的类消息中添加一个方法
public function getStatusString() {
return 'message.status.'.$this->status;
}
然后,在你的翻译文件中像这样处理它:
message.en.xlf
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="1">
<source>message.status.0</source>
<target>New</target>
</trans-unit>
<trans-unit id="2">
<source>message.status.1</source>
<target>Sent</target>
</trans-unit>
<trans-unit id="3">
<source>message.status.2</source>
<target>Delivered</target>
</trans-unit>
</body>
</file>
</xliff>
关于php - 在 Symfony2 和 SonataAdmin 中翻译数字状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16859977/