如何在cloudControl上使用Symfony2和MongoDB?

时间:2014-06-16 20:42:10

标签: php mongodb symfony cloudcontrol

我想在cloudControl(像heroku这样的PaaS提供程序)容器上使用Symfony2和MongoDB。现在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

由于MongoDB是一个PaaS AddOn,我没有静态连接凭据。它们由容器生成。 cloudControl提供了这种方式来访问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);

如何将这些动态获取的凭据导入Symfony2 config.yml

1 个答案:

答案 0 :(得分:2)

解决方案是使用Symfony2 Miscellaneous Configuration

因此,请创建包含以下内容的app/config/credentials.php文件:

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

然后在app/config/config.yml添加:

imports:
    - { resource: credentials.php }

如果这可以解决您的问题,请告诉我。