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

时间:2018-02-07 07:26:14

标签: php laravel laravel-5.5

假设我在price_list文件中设置了null app.php选项:

'price_list' => null,
应该在我的应用运行时根据某些条件设置

price_list。例如,如果登录用户具有administrator角色,那么我应该从price_list表中获取适当的值:

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

所以在这里,我发现要这样做,我应该使用服务提供商,然后执行this Answer中提到的所有功能。但我不知道哪种方法使用启动注册方法和单例绑定方法是正确的?< / p>

2 个答案:

答案 0 :(得分:1)

documentation中所述,您绝不应尝试在register方法中注册任何事件监听器,路由或任何其他功能。
否则,boot完全符合您的需求,这是在所有其他服务提供商注册后调用的 所以你可以这样做:

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

答案 1 :(得分:-1)

boot()方法中执行此操作。来自the docs

  

register方法中,您应该只将事物绑定到服务容器中。

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

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