在哪里设置配置选项? boot() 或 register() ? singleton() 或 bind()



>假设我有一个price_list选项,我设置了该选项以app.php文件中null

'price_list' => null,

price_list应根据运行应用时的某些条件进行设置。 例如,如果登录用户具有administrator角色,那么我应该从price_list表中获取适当的值:

if (Some Condition){
$pricelist  = fetch from price_list table
Config::set('price_list' ,$price_list);
}

所以在这里,我发现要做到这一点,我应该使用服务提供商,然后按照本答案中提到的所有功能进行操作。但是我不知道使用引导注册方法以及单例绑定方法哪种方法是正确的?

如文档中所述,切勿尝试在register方法中注册任何事件侦听器、路由或任何其他功能。
否则,boot完全符合您的需求,在所有其他服务提供商注册后调用。
因此,您可以执行以下操作:

if (Auth::user()->isAdmin()) { //you can make the function in the model, here just an example
config()->set('price_list', 'blablabla);
}

boot()方法中执行此操作。从文档中:

register方法中,只应将内容绑定到服务容器中。

此外,您无需为此使用bind()singleton()方法。只需这样做:

public function boot()
{
config([price_list' => $price_list]);
}

最新更新