What is the right way to assign a unique id to request in Slim framework 3?

Hi there

I need suggestion on how could I implement the process of generating a unique id or request id for every request and then showing that unique id in the response.

My purpose is basically to provide a unique id to every request and saving that id in database and finally showing that id with processed data to user, so user can query on basis of that id next time.

What I have understood so far is, I should done this by using middleware.

I have created a function of processing data say: processed_data in class .

My routes is :

$app->group('/products', function() {
        new \Products($this);


 class Products
        public function __construct($app)
            $app->map(['GET','POST'], '/processed_data', [$this, 'processed_data']);
            $c = $app->getContainer();

        public function processed_data($request, $response, $next){

                    $data = array('name' => 'Bob', 'age' => 40);            

        /* I need to append $data in $response or in any container,
        instead of writting here using write() method so that I 
        can use my $data in middleware for final processing or 
        simply say adding a unique id with this $data.*/

                    return $response;



Middleware I created is:

   class SendStandardResponse
        public function __construct(){} 

        public function get_standard_request($request, $response, $next) {

        // here I saved the request in the database 
         /*I want here to generate a unique id say : XXXXXX .
        I am not sure where to append this unique id, either in 
        request or response or container. */

            return $request;

         * recode_Response
        public function send_stardard_esponse($request, $response, $next) {

            // here I saved the response in the database    
            /* get the output data from the processed_data function and add the unique id to response .
            And finally send the response with $data and unique id by merging /

            $data = array('name' => 'Bob', 'age' => 40, 'requestid' => 'xxxxxx');

            and send it with response


             return $response;

        public function __invoke($request, $response, $next)

            $this->get_standard_request($request, $response, $next);

            $response = $next($request, $response);

            $this->send_stardard_esponse($request,$response, $next);    

            return $response;

Hi @vijay - I haven’t looked or checked the code, but it seems fine - so all you need to do is add the request Id to the $request, something like:

$newRequest = $request->withAttribute('uniqueId', $uniqueId); 
return $newRequest;

You can then retrieve it anywhere you need it with $request->getAttribute('uniqueId');

I think that’s what you’re after anyway, or I’ve read it wrong :slight_smile: