Question

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

Was it helpful?

Solution

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);
}

OTHER TIPS

Well You can add application wide variable into config/autoload/global.php. (However i think all config array are merged down in process of page load. So other config also should work. ) For UUID Generator, I would suggest to make a module named like ProjectServices into vendor folder and define service for uuid generate (Ex. vendor\ProjectServices\src\ProjectServices\Service\UUIDGenerate.php) into that. You can define more services like global logger as per your requirements into that folder.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top