zend-framework2multiple-databaseson-the-fly

ZF2 How to get unloaded config file in controller?


The cenario
My application is divided by many agencies, each one with it's own database and database configuration file.

Before logging in, the user needs to send me an agency-id. In that request ZF2 load a non-agency db configutarion file (with SQLite database info) to validate if agency-id really exists.

The next requests are made to agency-specific-url so ZF2 load that agency's specific db configutarion file.

The problem
In the first request (to validate agency-id) after I validate it, I need to load the agency's specific database to fetch some info and return it.

I was thinking of loading that "unloaded agency database config file" in my controller, to instantiate a model with a DbAdapter containing the agency's database info for that, but I can't find a way to do it.

How can I do this or is there another way? Perhaps I should load every agency config file before ZF2's init but I don't know if that's the best solution.


Solution

  • To solve this I created an action that will return the agency's info. Inside the agency-id validate action, create a request for the above action and get it's response:

    // Create request to get agency's info
    $client   = new Client();
    $request  = new Request();
    $request->setMethod(Request::METHOD_GET);
    $explicitUrl = 'http://example.com/any/action';
    $request->setUri($explicitUrl);
    $response = $client->send($request);
    
    // The any/action route points to an action that return JSON data
    $json     = JsonDecoder::decode($response->getBody());
    
    // Now I can do whatenever I want
    $json->variable1...
    $json->variable2...
    $json->variable3...