更改队列作业中的语言环境

Changing Locale In Queue Job

我有一个修改器,可以将模型的主体转换为所需的翻译格式。

public function getTextAttribute() {
   return $this->constructText($this->body); // which does __($key, $value)
}

protected $appends = ['text'];

但是,一旦他们在排队的工作中,我无法更改区域设置,即使我传递 Eloquent Collection,它也会将它们更改为默认区域设置。

我尝试了什么:

  1. 在触发作业之前,将 $locale 和 $eloquentCollection 传递给作业。

    MyEvent::dispatch($collection, $language)
    

在我的工作中,

    public function __construct($collection, $language)
    {
       app()->setLocale($language);
       // if I log here, it logs the given locale as my current locale
       // but as soon as hits the get mutator, it goes back to default locale
    }

  1. 在我的 collection 中,我试着放一个 属性:

    class MyModel extends Model {
       public $locale = null;
    
    }
    

在我的工作中,

    public function __construct($collection, $language)
    {
       app()->setLocale($language);

       $collection->each(function($item) {
           $item->locale = $language;
       })
    }

并将修改器更改为:

    public function getTextAttribute() {
       if (!$this->locale) { 
           $this->locale = app()->getLocale(); 
       }

       return $this->constructText($this->body, $this->locale); 
       // which does __($key, $value, $locale) inside
    }

然而这也不起作用。当我登录 constructText() $locale - 它 returns 也是默认语言环境。

您有什么办法或解决办法吗?我想到的其他 2 种可能的解决方法是:

仅当您创建事件的新实例时才会调用事件的构造函数,然后 fired/dispatched。当包含需要广播的此事件的作业获得 运行 时,它只有序列化的有效负载可以使用。您需要尝试在作业的句柄方法调用的方法中设置区域设置或类似设置。这些广播事件将具有队列作业的 handle 方法调用的 broadcastAsbroadcastOnbroadcastWith 方法。您应该能够在其中一种方法中设置您需要的内容,因为它们将由工作人员 运行 的队列作业运行,因此它不是原始请求生命周期的一部分(除非事件已经实现 ShouldBroadcastNow,因为那样会使用 sync 驱动程序而不是队列工作人员)。