We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Bestway to alter the Request fields (or to store a per-request runtime-generated variable)

Hello, i want to assign each request a unique ID so i could monitor it in the Log. What would be the best way to do it in Phalcon?

Actually i generate the ID with uniqid function and try to apply it with Filters... But it seems too strange a such roundtrip with filters...

i just need to have a new globally-request accessible var generated on request entry (actually i do this in public/index.php) ...

[edit] Just now i've changed it to a more maintenable way. I'm using a custom service instantiated and injected directly in the DI, not shared.

Do you suggest a better way?

You could use the $di and register a new service as:

$di->set('request_id', function() {
    //Code to return the random id id that's unique/request
  }, true);

Yes, it's just what i did... as i've added other context info, i think there is no better way.

You can extend the Request object like this:

class MyRequest extends \Phalcon\Http\Request 
{
    public function getRequestId()
    {
        // One way to get a unique id
        $get = $this->get();
        $id  = sha1(json_encode($get));

        // Another way
        // $id = uniquid();
    }
}

and then register that in your DI container:

$di->set('request', new MyRequest(), true);

From there you can call from a controller:

$id = $this->request->getRequestId();
// Log it here