CakePHP database config quick-tip

Most CakePHP programmers have seen this simple way of storing the development and production database settings in one file:

  1. class DATABASE_CONFIG {
  2.     var $prod = array(
  3.        
  4.         'database' => 'live_mysite'
  5.     );
  6.  
  7.     var $test = array(
  8.        
  9.         'database' => 'local_mysite'
  10.     );
  11.  
  12.    // the construct function is called automatically, and chooses prod or dev.
  13.     function __construct() {
  14.         //check to see if server name is set (thanks Frank)
  15.         if(isset($_SERVER['SERVER_NAME'])){
  16.             switch($_SERVER['SERVER_NAME']){
  17.                 case '127.0.0.1':
  18.                     $this->default = $this->test;
  19.                     break;
  20.                 default:
  21.                     $this->default = $this->prod;
  22.                     break;
  23.             }
  24.         } else { // we are likely baking, use our local db
  25.             $this->default = $this->test;
  26.         }
  27.     }

If you haven’t, check out Edward A. Webb’s original post from 1998 2008.

This same technique can be used in the bootstrap.php file for other settings that change based on the server, for instance GoogleMap keys:

  1. if ( strpos( $_SERVER['HTTP_HOST'],'MySite.com') !== false)
  2.     Configure::write('GMAP_KEY', 'ABQIAA…qcPrtZgKHQ');
  3. else
  4.     Configure::write('GMAP_KEY', 'ABQIAB…e6qfWeeY8Q');

However, when baking a model, the database file only defines two types: prog and test so you pick one and end up with a model file with a line like:

  1. var $useDbConfig = 'test';

in your baked model that doesn’t cause any problems right up until upload it to your live server late one night and start getting errors about being unable to make a connection- guess who did that?

The solution is simple: just define a default

  1. var $default;

somewhere in the file, now when you bake cake will give you the option of using the default connection which won’t add any problem-causing $useDbConfig to your model.

Hope this saves someone 20 minutes :)

One thought on “CakePHP database config quick-tip

  1. Glad my article helped you out!

    1 – Normally I don’t allow re-posting of content without permission, but since your site is ad-free as well, I will allow the use of code. (please get permission next time)

    2 – The article is from June 2008, not 1998 ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>