What is the best way in CakePHP to have multiple database configuration that is going to be used based on environment?
Say I have a staging, prod and dev server.
Thank you,
Tee
First open app/Config/database. php file in any code editor. The default database is public $default , if you want to use other database(db2, db3) you need to initialize new database in your Model using $useDbConfig predefined cakephp method see example.
You can set it in your constructor.
class DATABASE_CONFIG {
var $live = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'mysql.live.com',
'login' => 'root',
'password' => '',
'database' => '',
'prefix' => '',
);
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => '',
'prefix' => '',
);
public function __construct() {
if (isset($_SERVER) && isset($_SERVER['SERVER_NAME'])) {
if (strpos($_SERVER['SERVER_NAME'], 'localhost') === false) {
$this->default = $this->live;
}
}
}
}
This will basically switch your configuration based on where you are.
I got this (my development domain ends with '.dev');
In Bootstrap.php
define('IS_LIVE',!(strpos($_SERVER['SERVER_NAME'], 'dev') !== false));
In database.php
<?php
class DATABASE_CONFIG
{
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => '127.0.0.1',
'login' => 'xxxx',
'password' => 'xxxx',
'database' => 'xxxx',
'prefix' => '',
);
var $production = array(
'driver' => 'mysql',
'persistent' => false,
'host' => '127.0.0.1',
'login' => 'xxx',
'password' => 'xxx',
'database' => 'xxxx',
'prefix' => '',
);
function __construct()
{
if (IS_LIVE) {
$this->default = $this->production;
} else {
$this->default = $this->default;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With