如何在流明中使用preferredLocale? [英] How to use preferredLocale in lumen?

查看:70
本文介绍了如何在流明中使用preferredLocale?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着Laravel 5.7的发布,Illuminate \ Notifications \ Notification类开始提供一种设置所需语言的语言环境方法.格式化通知时,应用程序将更改为该区域设置,格式化完成后,应用程序将还原为以前的区域设置.这是此功能的示例:

With the release of Laravel 5.7 the Illuminate\Notifications\Notification class started offering a locale method to set the desired language. The application will change into this locale when the notification is being formatted and then revert back to the previous locale when formatting is complete. Here is an example of this feature:

$user->notify((new InvoicePaid($invoice))->locale('ar'));

我只需要在流明(最新版本)中使用此功能,但是当我实现该功能时,例如

I just need to use this feature in lumen (latest version) but when I implement that Like documentation said I got an error

Call to undefined method Laravel\Lumen\Application::getLocale() 这是因为在流明应用程序中没有getLocalesetLocale方法.所以有什么办法可以解决这个问题.

Call to undefined method Laravel\Lumen\Application::getLocale() and this because there is no getLocale or setLocale methods in lumen application.. so any ideas to solve this.

推荐答案

流明和Laravel之间的区别在于,在Laravel中,您称为Application->setLocale().

Difference between Lumen and Laravel is that in Laravel you call Application->setLocale().

这完成了三件事,如上所述:

This does three things, as outlined above:

  1. 设置配置app.locale
  2. 在翻译器上设置区域设置
  3. 触发locale.changed事件

但是

在流明中,您可以直接使用app('translator')->setLocale()App::make('translator')->setLocale()

In Lumen though, you would call the translator directly with app('translator')->setLocale() or App::make('translator')->setLocale(),

所以这里的区别是不会自动设置config变量,也不会触发locale.changed事件.

so the difference here is that the config variable will not be set automatically and the locale.changed event will not be fired.

Laravel的Application类还更新配置并触发事件:

Laravel's Application class also updates the config and fires an event:

public function setLocale($locale)
{
    $this['config']->set('app.locale', $locale);
    $this['translator']->setLocale($locale);
    $this['events']->fire('locale.changed', [$locale]);
}

在Laravel中,getLocale只是读取config变量:

and in Laravel, getLocale is just reading the config variable:

public function getLocale()
{
    return $this['config']->get('app.locale');
}

对于翻译而言,重要的是翻译. Laravel的跨性别助手看起来像这样:

For translations thought, it's the translator that matters. Laravel's trans helper looks like this:

function trans($id = null, $parameters = [], $domain = 'messages', $locale = null)
{
    if (is_null($id)) {
        return app('translator');
    }
    return app('translator')->trans($id, $parameters, $domain, $locale);
}

您需要使用上述3种方法使您的应用程序扩展另一个类

这篇关于如何在流明中使用preferredLocale?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆