skip to Main Content

I am using Lumen to build an API and I am trying to figure out what the best way is to keep data in memory for the entire duration of a request. The idea is to avoid writing to a database or using something like Redis or Memcached. So, basically, I want to create a global variable that I can manipulate along the way until the http action is complete and then it can disappear from memory.

For example, if I send a POST request with a body to my /api/v1/postme route, I want to accept the POST request and make another call out to another service to retrieve some data. I want to take that data and merge it with the original data from the POST request. I want to then take that newly merged data and send it as the response after some more translations.

I have read in some posts online that one can use the app config variables in the .env file as a temporary store of data within memory, but I was wondering if there was a different or possibly better way to accomplish this.

I read through the Laravel/Lumen documentation and it seems that I could be writing to the Lumen cache but I think that would result in making a database connection, which is not what I am looking for.

2

Answers


  1. If you want to use the config module of lumen follow this.

    When request arrives, hits myfunc

    controller.php

        public function myfunc(Request $request){
            app('config')->set('someuniquekey', $request);
            // call some other api
            $client = new GuzzleHttpClient(..);
            $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
        }
    
    Login or Signup to reply.
  2. You can have it like so

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

    That’s a pretty simple approach

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search