【问题标题】:How to preserve request data Laravel Lumen through the lifetime of a request?如何在请求的整个生命周期中保留请求数据 Laravel Lumen?
【发布时间】:2020-05-26 09:21:56
【问题描述】:

我正在使用 Lumen 构建一个 API,我正在尝试找出在整个请求期间将数据保存在内存中的最佳方法。这个想法是避免写入数据库或使用RedisMemcached 之类的东西。所以,基本上,我想创建一个全局变量,我可以一直操作它,直到 http 操作完成,然后它可以从内存中消失。

例如,如果我向 /api/v1/postme 路由发送带有正文的 POST 请求,我想接受 POST 请求并再次调用另一个服务以检索一些数据。我想获取该数据并将其与来自POST 请求的原始数据合并。然后,我想获取新合并的数据,并在进行更多翻译后将其作为响应发送。

我在网上的一些帖子中读到,可以使用.env 文件中的应用程序配置变量作为内存中数据的临时存储,但我想知道是否有不同的或可能更好的方法来实现这一点。

我阅读了 Laravel/Lumen 文档,似乎可以写入 Lumen 缓存,但我认为这会导致建立数据库连接,这不是我想要的。

【问题讨论】:

  • 如果你的意思是 php 的生命周期,你可以简单地跨类传递变量,或者你也可以在 Cache 门面中设置它。
  • 你也可以访问 \request() 助手,它将包含我打赌的数据
  • @emad,很有趣,我想尝试使用您的跨类传递变量的想法。如何访问模型中的 HTTP 数据?

标签: php laravel httprequest lumen


【解决方案1】:

如果你想使用 lumen 的 config 模块,请按此操作。

当请求到达时,点击 myfunc

controller.php

    public function myfunc(Request $request){
        app('config')->set('someuniquekey', $request);
        // call some other api
        $client = new \GuzzleHttp\Client(..);
        $response = $client->post(..);


        //retrive the value stored in config
        $request= config('someuniquekey');

        //merge $request and $response


        //This can be accessed in class method/ helper function too
        $this->func2();
        func3();
    }

    private function func2(){
        $request= config('someuniquekey'); // WORKS
    }

helpers.php

    function func3(){
        $request= config('someuniquekey'); // WORKS
    }

【讨论】:

    【解决方案2】:

    你可以这样拥有它

    # Store it in request, for that run
    request()->request->add(['your_param'=>'yourvalue']);
    
    # Then access it from anywhere using
    request()->get('your_param');
    

    这是一个非常简单的方法

    【讨论】:

    • 可以在模型中访问吗?我假设此时只能在控制器内访问它。这个想法是我想为应用程序全局存储这些信息。
    • 是的,可以在任何地方使用request helper、\request()->get('your_param');,前提是它添加在模型代码之前的某个位置
    猜你喜欢
    • 2013-03-24
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    相关资源
    最近更新 更多