I'm using Zend-Framework2 and I'd like to log information about a request. Not all servers provide $_SERVER['UNIQUE_ID'], so I'd like to generate my own(Please see http://en.wikipedia.org/wiki/Universally_unique_identifier for the format).
In ZF2 everything is done within the modules, but I'd like to create an application-wide variable or constant with the unique ID in it. I can add it to index.php, but that's not the way to go I think... Another option is that the generation of the unique request id is being done in the onBootstrap method of the module that is called, but then I'm repeating myself and that is not desirable, I think.
Where should I ideally put the piece of code to generate the UUID and add it as an application-wide variable / constant?
Thanks in advance!
Similar question: Log each request in ZF2
Another option is that the generation of the unique request id is being done in the onBootstrap method of the module that is called, but then I'm repeating myself and that is not desirable, I think.
I think you're misunderstanding modules here Ivo. The onBootstrap
method is called for every module that has one, regardless of which module is ultimately resolved and dispatched for the current request. It's not a case of the router finding the controller and then bootstrapping that single module, they're all bootstrapped by the ModuleManager before any routing takes place.
From that point of view, you can place it in a module, generating the UUID on bootstrap. To make it available site wide in a convenient manner, set that value as a service and it's then available anywhere from the service manager.
public function onBootstrap(EventInterface $e) {
$sm = $e->getApplication()->getServiceManager();
$uuid = isset($_SERVER['UNIQUE_ID']) ? $_SERVER['UNIQUE_ID'] : yourUUIDGeneratingMethod();
$sm->setService('UUID', $uuid);
}