【问题标题】:Symfony: Format date in entity depending on localizationSymfony:根据本地化在实体中格式化日期
【发布时间】:2018-02-16 09:05:47
【问题描述】:

我的 Symfony 4 项目中有以下实体

class Post
{
  /**
   * @var string
   *
   * @ORM\Column(name="date_string", type="string", length=11)
   */
  private $dateString;

  public funtion getDateString()
  {
    return $this->dateString;
  }
}

我知道,我可以为此使用 \DateTime,但这对我的情况无关紧要 ;)

我想要的是,根据用户的本地化转换日期字符串。因此我创建了一个新的翻译并使用键“dateFormat”来设置每个本地化的日期格式。

messages.en.yaml

  dateFormat: "m/d/Y"

messages.de.yaml

    dateFormat: "d.m.Y"

我的问题是:获取格式化日期字符串的最佳做法是什么?我写了一个存储库方法,但我不喜欢这个解决方案。当我访问该方法时,我总是必须获取存储库,并且在 Twig 模板中使用它并不方便。

后存储库:

public function getFormattedDateString(Post $post): string
{
  $dateTime = new \DateTime($post->getDateString());
  $dateFormat = $this->translator->trans('dateFormat');

  return $dateTime->format($dateFormat);
}

我宁愿直接从实体中使用该方法。像这样的:

$post->getFormattedDate();

但这不起作用,因为我需要将 TranslatorInterface 注入到实体中。这很糟糕。或者有没有办法修改 getDateString() 方法的结果? (注释?)

你会如何解决这个任务?非常感谢

【问题讨论】:

    标签: php symfony date format entity


    【解决方案1】:

    我假设您不想使用 IntlDateFormatter 并想重新发明一种翻译日期的方法。
    我会做一个服务LocaleDateFormatter,而不是当您需要将日期转换为语言环境格式的日期(以及在树枝模板上使用树枝过滤器)时可以使用的服务

    __construct(TranslatorInterface $translator)
    {
       $this->translator = $translator;
    }
    
    public function getFormattedDateString($dateString): string
    {
      $dateTime = new \DateTime(dateString);
      $dateFormat = $this->translator->trans('dateFormat');
    
      return $dateTime->format($dateFormat);
    }
    

    【讨论】:

      【解决方案2】:

      也许您可以创建一个服务来公开一个函数,该函数将您的用户作为参数。它会解析你需要的日期字符串。

      例如,您可以创建一个DateFormatResolverInterface,它将实现resolveFormat(User $user)。然后,创建一个实现接口的RequestLocaleDateFormatResolver 类,并解析resolveFormat() 函数内部的格式。您始终可以通过创建 new classimplements the interface 来更改解析格式的方式。

      然后,在需要时使用它:$this->get('acme.date_format_resolver')->resolveFormat($user);$this->get(DateFormatResolverInterface::class)->resolveFormat($user);

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-04
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多