Home > CakePHP, Development, Frameworks, Labs, PHP > Using more than one database connection in CakePHP

Using more than one database connection in CakePHP

April 10th, 2008

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.

CakePHP, Development, Frameworks, Labs, PHP , , , , , , , ,

  1. February 24th, 2009 at 05:57 | #1

    you have a typo my friend.

    var $oher = array( …

    should be
    var $other = arra( …

  2. February 24th, 2009 at 09:50 | #2

    Thanks ajmacaro

  3. March 17th, 2009 at 12:42 | #3

    Thanks,

    i’ve been searching for a way how to get data from OSCOmmerce DB to be viewed on CakePHP CMS website.

  4. March 30th, 2009 at 23:52 | #4

    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!

  5. June 10th, 2009 at 05:02 | #5

    I have used it !it is very well!

  6. June 16th, 2009 at 16:19 | #6

    Veryy Nice Thnx

  1. April 10th, 2008 at 16:17 | #1

*
To prove that you're not a bot, enter this code
Anti-Spam Image