在Yii2中为单个请求设置全局可用代码

问题描述:

I'm using Yii2 and I have a situation where I want to make some code globally available, but only for that request.

My use case is based on this question where I am doing some permission checks via a matchCallback.

I need to run a few different permission checks and if I can't do them all in the one place via the matchCallback (because I can't access all of the data I need it seems at that specific time) - then I am trying to avoid having to run the query again.

So, I was wondering if I could store data retrieved from the database such as a JSON encoded permission array within my matchCallback functionaltiy so I could then access that array within another action.

I know I could use flash data, but that seems like it is more meant for the next request. Is there anything available for just the current request or should I just use flash data anyway?

我正在使用 Yii2 code>我有一种情况我想制作一些代码 全局可用,但仅 em>该请求。 p>

我的用例基于这个问题,我通过 matchCallback code>进行一些权限检查。 p> \ n

我需要运行一些不同的权限检查,如果我不能通过 matchCallback code>在一个地方完成所有这些检查(因为我无法访问所有数据) 需要它似乎在那个特定的时间) - 然后我试图避免再次运行查询。 p>

所以,我想知道我是否可以存储从数据库检索的数据,如 我的 matchCallback code>功能中的JSON编码权限数组,因此我可以在另一个操作中访问该数组。 p>

我知道我可以使用 flash data code >,但那 似乎它更适用于 next code>请求。 是否只有当前请求可用或者我是否应该只使用 flash data code>? p> div>

I wonder what would be the best practice here too... As for me I'd use Yii::$app->params array for that purpose. It does not look very good as it's called 'params' and supposed to be some custom parameters like 'adminEmail' etc. But it works nice: it is readable and writable from everywhere and if you set some of its keys or values dynamically it will long only for this particular request - just what you want. It's like:

Yii::$app->params['myKey'] = $myValue;
...
$myValue = Yii::$app->params['myKey'];