Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use the Laravel Context Event: hydrated and dehydrating #45

Open
yankewei opened this issue Nov 13, 2024 · 0 comments
Open

How to use the Laravel Context Event: hydrated and dehydrating #45

yankewei opened this issue Nov 13, 2024 · 0 comments
Labels

Comments

@yankewei
Copy link
Owner

yankewei commented Nov 13, 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::dehydrating(function (Repository $context) {
    $context->addHidden('locale', Config::get('app.locale'));
});

Context::hydrated(function (Repository $context) {
    if ($context->hasHidden('locale')) {
        Config::set('app.locale', $context->getHidden('locale'));
    }
});

和其他方法有什么区别

使用 Context::add 方法也可以实现在 job 和 worker 之前共享数据,例如:

Context::add("ping","pong");
LogContextConsumer::dispatch("hahaha");

在 job 被消费的时候,Context 也会被自动添加到 worker 中。但是如果想要让每一个 job 被分发的时候自动追加一些 context 就需要用到 Event,例如自动添加当前的登录用户到 Context 中,这样在 job 的消费的时候就可以拿到 job 被分发时的登录用户,方便我们做一些用户校验之类的。

使用限制

Event 是否可以写到其它的 ServiceProvider 中

文档中说需要把这两个事件定义到 AppServiceProvider 中的 boot 方法中。

@yankewei yankewei added Laravel and removed Laravel labels Nov 13, 2024
@yankewei 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant