I can’t be the only person who has ever googled to try and find a way to have propel automatically choose which database to connect to, based on some criteria or other.

In my case, I have dev versions of sites on the same server as live versions, so they need to look at a database with a different name. I do this all the time, so expected to find the answer quickly on google.

I didn’t! I then tried to guess/look at propel and work out how to give it multiple database configs, but I couldn’t. It can have multiple configs, but not for use instead of each other, it tries to use them all I think.

I did find a solution after a bit though, and since I can’t find it written up, I thought I would!

When you run propel-gen, propel creates a file called <projectname>-conf.php in the build/conf directory of your project.

If you open this, you can easily see where it’s put the details in from your runtime-conf.xml file.

To work with multiple databases:

  1. Create a copy of this file for each environement – i go with <project name>-conf-dev.php and <project name>-conf-live.php.
  2. Edit these files to suit (replace the db username/password with the relevant ones for that environement.
  3. When you set up propel, you will have somewhere placed a call to Propel::init – and guess what? You pass this an argument to tell it where to load the config file from. So you need to create whatever logic you need to ensure that it loads either the dev or the live version of the file.

EG:

If (strpos($_SERVER['SERVER_NAME'], “somepieceofdevurl”)) {
    $propelconf = ‘/path/to/project-conf-dev.php’;
} else {
    $propelconf = ‘/path/to/project-conf-live.php’;
}

Propel::init($propelconf);

Thats all there is to it. You don’t need to worry about the config in build.properties, as thats for the propel-gen command and isn’t needed at runtime.

Hopefully you have Propel::init callled from some common include file! Otherwise it’ll be a lot of edits.

Remember too that propel won’t update these copies of the files if you ever edit the runtime-conf.xml file – you’ll have to do that yourself.