2

I would like to use Symfony2 and MongoDB on a cloudControl (PaaS provider like heroku) container. Now Symfony2 supports the usage of MongoDB:

# app/config/config.yml
doctrine_mongodb:
    connections:
        default:
            server: mongodb://localhost:27017
            options: {}
    default_database: test_database
    document_managers:
        default:
            auto_mapping: true

And as MongoDB is a PaaS AddOn, I don't have static connection credentials. They're generated by the container. cloudControl offers this way to access the credentials in PHP:

$credfile = file_get_contents($_ENV['CRED_FILE'], false);
$credentials = json_decode($credfile, true);
$uri = $credentials["MONGOLAB"]["MONGOLAB_URI"];
$m = new Mongo($uri);
$db = $m->selectDB(myDbName);
$col = new MongoCollection($db, myCollection);

How can I get these dynamically fetched credentials into Symfony2's config.yml?

1 Answer 1

2

The solution would be to use Symfony2 Miscellaneous Configuration.

So, create app/config/credentials.php file with below content:

<?php
if (isset($_ENV['CRED_FILE'])) {

    // read the credentials file
    $string = file_get_contents($_ENV['CRED_FILE'], false);
    if ($string == false) {
        throw new Exception('Could not read credentials file');
    }

    // the file contains a JSON string, decode it and return an associative array
    $creds = json_decode($string, true);

    // overwrite config server param with mongolab uri
    $uri = $creds["MONGOLAB"]["MONGOLAB_URI"];
    $container->setParameter('doctrine_mongodb.connections.default.server', $uri);
}

Then in your app/config/config.yml add:

imports:
    - { resource: credentials.php }

Let me know if this solves your problem.

Sign up to request clarification or add additional context in comments.

6 Comments

Looks really nice, will try that out. But btw: Why are you checking !empty($_SERVER['HTTP_HOST'])?
We have used it to distinguish between PaaS and local env - you can ignore it!
Okay, and how about the $container? Is the container automatically available in that PHP file or do I have to inject it manually?
It should be automatically available.
Yeah, just tested it. The $container is known and doesn't has to be injected. Wow, this is such an easy way. I used to dynamically set some parameters via Services and kernelListeners, but this is easy as hell; thanks a million!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.