Using more than one database connection in CakePHP

Probably is pretty obvious for most of the advanced users, but when I started my experience with CakePHP I read a lot of configuring a database, but not multiple ones. There are articles how to use database for development and for production without changing anything but rewriting a function in DATABASE_CONFIG class.

These days we need to choose way of splitting the functionality and we have to decide: Shall we use different databases or shall we put a prefix for every table. So far we choose to use prefix, but I dig into this and I realized that every model could be attached to different database.

Here is the example how to do this:

class User extends AppModel {
   ...
   var $useDbConfig = 'other';
   ...
}

so this variable $useDbConfig is the trigger which linking the model to different databases defined in the DATABASE_CONFIG class.

class DATABASE_CONFIG {

    var $default = array(
        'driver' => 'mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'user1',
        'password' => 'pass1',
        'database' => 'db1',
        'prefix' => ''
    );
   
    var $other = array(
        'driver' => 'mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'user2',
        'password' => 'pass2',
        'database' => 'db2',
        'prefix' => ''
    );
}

When I am thinking more and more it’s quite handy, especially if you want to connect different databases like Oracle, MySQL or Postgresql together.

Of course this could be created automatically with Bake script, because before start baking Model(s) it ask which connection do you want to use. So it’s pretty easy.

Hope this help somebody.

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

13 thoughts on “Using more than one database connection in CakePHP

  1. Pingback: Using more than one database connection in CakePHP | White Sands Digital

  2. I am so used to Zend PHP that I get confused when switching to Cake! This was exactly what I was looking for to switch from Postgres to MySQL. Your posts are very helpful, so please keep them up!

  3. Should we use a variety of databases, or should we set a prefix for each table. So far, we have decided to use the prefix.

Leave a Reply

Your email address will not be published. Required fields are marked *