Search code examples
phpcakephpcakephp-2.0appfog

How to config cakephp 2.2 database connection with appfog service


I'have some problem to config cakephp database connection with appfog service.

AppFog provides JSON database config by VCAP_SERVICES variable like this

 {
    "mysql-5.1" =     (
                {
            credentials =             {
                host = "ap01-user01.c0ye1hvnkw6z.ap-southeast-1.rds.amazonaws.com";
                hostname = "ap01-user01.c0ye1hvnkw6z.ap-southeast-1.rds.amazonaws.com";
                name = ?????????????;
                password = ????;
                port = 3306;
                user = ?????;
                username = ???????????;
            };
            label = "mysql-5.1";
            name = "???????-mysql-56200";
            plan = free;
            tags =             (
                mysql,
                "mysql-5.1",
                relational
            );
        }
    ); }

In cakephp database config file like this

public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => $mysql_config["hostname"],
        'login' => $mysql_config["username"],
        'password' => $mysql_config["password"],
        'database' => $mysql_config["name"],
        'prefix' => '',
        //'encoding' => 'utf8',
    );

How to fix this problem?


Solution

  • You will want to parse the json into an array (if you only have ONE mysql db bound to the app, if you have more you will need to change the "0" to another number to reflect the second bound mysql service):

    $services = getenv("VCAP_SERVICES");
    $services_json = json_decode($services,true);
    $mysql_config = $services_json["mysql-5.1"][0]["credentials"];
    
    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => $mysql_config["hostname"],
        'login' => $mysql_config["user"],
        'password' => $mysql_config["password"],
        'database' => $mysql_config["name"],
        'port' => $mysql_config["port"],
        'prefix' => '',
        //'encoding' => 'utf8',
    );
    

    The above changes "username" to "user" and basically follows the premise of what appfog does with Wordpress: https://github.com/appfog/af-php-wordpress/blob/master/wp-config.php