duanrang2627 2018-11-27 15:59
浏览 490

Laravel 5.6 - 全局和动态变量

I have an API with laravel 5.6 and I need to create global variables that throughout the application can have their value changed, however I am having problems.

Example: - At the first request, the value of this variable as "test"; - In the second request I want to get the current value, which should be "test";

  1. I tried initially to use the config, but it did not work;
  2. I tried to use Session, but I had the same problem;
  3. I tried to set a variable in the "super controller", where all controllers extended to it, it did not work.

The value of the variable is only valid during the execution of the request, that is, I make a request to the controller aaaControler, this makes use of other controllers, within the same request the value persists, but ends in the return.

I thought of persisting in the database, creating a reference and always fetching this value there, but will this be the best way?

I ask for help in this matter.

Thank you.

  • 写回答

2条回答 默认 最新

  • duancong6937 2018-11-27 16:24
    关注

    If you need to have a "global" variable just for one request, accessible in every class of your project, I think a good solution is to set a config value at runtime. The config helper can be used both for reading as writing a value that will not persist on another request.

    You can set a value wherever you want:

    config(['any.key.you.want' => 'Some value']);
    

    And read it everywhere:

    config('any.key.you.want');
    => 'Some value'
    

    This works fine if you use the other controllers by instantiating it and calling its methods (what I think is not good for your code organization – you should probably use a service class).

    If you use other controllers using HTTP requests, it will not work. If this is your case, probably the best solution is to persist it to the database – as you proposed – or to use session. You store the value using one of these and then clear after your HTTP requests:

    session()->put('any.key.you.want', 'Some value');
    // make http request to another controller
    session()->forget('any.key.you.want');
    

    In the controller called by the HTTP request, you can get a session value:

    session('any.key.you.want');
    => 'Some value'
    

    If your HTTP request is async, you will probably run into some race conditions.

    评论

报告相同问题?

悬赏问题

  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿