问题
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()
and this because there is no getLocale
or setLocale
methods in lumen application.. so any ideas to solve this.
回答1:
Difference between Lumen and Laravel is that in Laravel you call Application->setLocale()
.
This does three things, as outlined above:
- Set config
app.locale
- Set Locale on the translator
- Fire the locale.changed event
In Lumen though, you would call the translator directly with app('translator')->setLocale()
or App::make('translator')->setLocale()
,
so the difference here is that the config variable will not be set automatically and the locale.changed event will not be fired.
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]);
}
and in Laravel, getLocale is just reading the config variable:
public function getLocale()
{
return $this['config']->get('app.locale');
}
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);
}
You need to make your application extends another class with the above 3 methods
回答2:
You can Extend your Laravel\Lumen\Application
in a new class and make $app
variable take an instance from your new class in your bootstrap\app.php
file
1- create the new class like this:
<?php namespace App\Core;
use Laravel\Lumen\Application as Core;
class Application extends Core
{
/**
* @param $locale
*/
public function setLocale($locale): void
{
$this['config']->set('app.locale', $locale);
$this['translator']->setLocale($locale);
$this['events']->fire('locale.changed', [ $locale ]);
}
public function getLocale()
{
return $this['config']->get('app.locale');
}
}
2- make an instance from your new class ex:
$app = new App\Core\Application(
realpath(dirname(__DIR__) . '/')
);
来源:https://stackoverflow.com/questions/54216880/how-to-use-preferredlocale-in-lumen