Change Database
A wiki page to collect different ways of switching Database settings based on different criteria. As with all things posted by me, keep in mind that this is unsupported and WORKS FOR ME in PHP 4 with MySQL
Based on request IP Address
So I wanted to be able to have the database that a CakePHP app used based on if the connecting machine was my development machine or if it was other users. There doesn’t seem to be a built in way to do this so I added another var to my config/database.php file and a constructor that looked like this.
class DATABASE_CONFIG { var $default = array( 'driver' => 'mysql', 'host' => 'localhost', 'login' => 'www', 'password' => '', 'database' => 'project_name', 'prefix' => '' ); var $dev = array( 'driver' => 'mysql', 'host' => 'localhost', 'login' => 'www-test', 'password' => '', 'database' => 'project_name-test', 'prefix' => '' ); function DATABASE_CONFIG () { // php 4 if ($_SERVER['REMOTE_ADDR'] == 'development.machine.ip') { $this->default = $this->dev;} } function __construct () { // php 5 UNTESTED BY ME if ($_SERVER['REMOTE_ADDR'] == 'development.machine.ip') { $this->default = $this->dev;} }
You would want to change the ‘development.machine.ip’ for the machine’s ip you are working on.
You could also just change the prefix value as well if your database was set up that way... Implementation detail is left up to the reader.
Based on request url
If you want to unit test your application, you cannot switch the database configuration based on the IP address, as you usually run the unit tests on the same machine you develop. So we have to switch the database configuration based on the request uri:
function __construct () { if (strstr($_SERVER['REQUEST_URI'], '/tests')) { $this->default = $this->test; } }
Based on DEBUG Level
You can simply change the condition above to something like
if (DEBUG > 0)
Other notes and comments
I think it should be possible to do a similar trick to change the DEBUG setting in the config/core.php file with something like (untested)
if ($_SERVER['REMOTE_ADDR'] == 'development.machine.ip') { define('DEBUG',2); } else { define('DEBUG',0); }
It would be a nice feature if there was a special kind of route or path like /admin or /bare that would enable one to set things like this perhaps /dev?