Switching CakePHP debug mode based on URL

For me I like to maintain at least two versions of any code base. One for development and one for production. For larger projects where an approval process tends to occur slowly one would also need to have a client testing/staging version as well. Each of those versions ideally should operate differently and use at least different databases.

To manage all these versions and configurations one could branch and update the database configuration files manually each time. However I believe the best way is to have the code detect what URL it is in and change settings based on the URL detected. Therefore if the cake application is being access from http://dev.example.com it will retrieve all data from the development database.

Setting this up is quite easy and I do this before I begin every project. The first step is to alter app/config/core.php, which is where the debug mode is normally specified. In it you will want to include a function before everything else to detect whether or not the application is being accessed from the development URL. The code required is below:

function dev() {
if (isset($_SERVER) and preg_match('/^dev/', $_SERVER['HTTP_HOST'])) {
return true;
} else {
return false;

Then you will make your core config file's debug mode line be conditional based on the results of your dev() function.

if (dev()) {
Configure::write('debug', 2);
} else {
Configure::write('debug', 0);

By placing the dev() function in the core configuration file it means that it will be available to all files in your application. The config file is imported even earlier than the bootstrap file.

To make your database configuration switch based on the URL create the following function in app/config/database.php

function DATABASE_CONFIG() {
if (dev()) {
$this->default['database'] = 'mydevdb';

The above code assumes you have created a mirror development database the same as your live version with the same login and password.

The dev() function can also be used in emails, which allows for simplified email debugging, which I will write about in another tip, but if you want a quick method simply update any destination email with your own to allow you to test all email functions with live data without having puzzled clients.


daniouyea said...

good idea! I was looking for something like this, because setting debug=2 in beforeFilter doesn't work.

Post a Comment