You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
yankewei
changed the title
How to use the Laravel Context Event: hydration and dehydration
How to use the Laravel Context Event: hydrated and dehydrating
Nov 16, 2024
Laravel Context
Laravel 在 11 版本中引入了 Context 概念,允许你在请求,队列或者 command 中共享一些数据。在 Context 中添加一些 Key 后,在任何地方打日志,那么日志的 context 信息会默认包含 Context 对象中的一些 key 和 value。详情可以参考 Laravel Context 文档。
Context Event
Laravel 添加了两个事件到 Context 中,hydrated 和 dehydrating。hydrated 是在 queue job 被消费的时候触发,dehydrating 在 job 被 push 到队列的时候触发。
Event 的用法
只需要在 AppServiceProvider 的 boot 方法中加入以下代码即可:
和其他方法有什么区别
使用 Context::add 方法也可以实现在 job 和 worker 之前共享数据,例如:
在 job 被消费的时候,Context 也会被自动添加到 worker 中。但是如果想要让每一个 job 被分发的时候自动追加一些 context 就需要用到 Event,例如自动添加当前的登录用户到 Context 中,这样在 job 的消费的时候就可以拿到 job 被分发时的登录用户,方便我们做一些用户校验之类的。
使用限制
Event 是否可以写到其它的 ServiceProvider 中
文档中说需要把这两个事件定义到 AppServiceProvider 中的 boot 方法中。
The text was updated successfully, but these errors were encountered: