Ease Deployment with Automatic Server Check

Take a peak at the CakePHP manual on configuration and you'll see that you can have two database configurations (and theoretically more, I suppose). Normally you'd have one for your test environment, and one for your live environment.

The manual recommends setting the $useDbConfig variable to the configuration of choice in each of your models. Certainly, this isn't very practical when it comes to deployment. So why not put it in app_model.php? app_model.php should be in your /app/ folder. If it's not, copy the one from /cake/app_model.php and place it in your /app/ folder. From here you can put in anything that should apply to all models.

class AppModel extends Model {
var $useDbConfig = 'test';
}

But we'd still have to change it every time we upload it to the live server. Instead, have it check which server the request is coming from and set it automatically.

class AppModel extends Model {
function __construct()
	{
	  $this->useDbConfig = $_SERVER['HTTP_HOST'] == 'devserver'?'test':'default';
	  parent::__construct();
	}
}

Just change devserver to whatever the hostname is of your dev server and you're off to the races. If you really wanted to keep things separated, you could even place the devserver string in /app/config/core.php

Published July 16, 2006 · Updated July 16, 2006
Categorized as CakePHP
Short URL: https://snook.ca/s/688

Conversation

3 Comments · RSS feed
Kalt said on June 04, 2007

Useful. Just one detail : it's recommended to use env('HTTP_HOST') instead of $_SERVER['HTTP_HOST'].

I'm using your script on my site, eveything works perfectly, until I use sanitize...
$sanitizer = new Sanitize();
$sanitizer->clean($this->data); // Don't work
Or
$sanitizer->clean($this->data, $this->MyModel->useDbConfig); // Don't work either

Any idea ?

Kalt said on June 04, 2007

It appears that is a bug... I have open a ticket :
https://trac.cakephp.org/ticket/2712

Peter A. Shevtsov said on January 20, 2009

It seems that this method doesn't work in CakePHP 1.2

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.

Want to learn about scaling CSS for large projects?

I'm available for full and half-day workshops on scalable CSS architecture. I can provide on-site training for your team. Interested?
Get in touch.