9

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

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I found this great article that provides a pretty robust way of setting up this method of managing DB profiles based on environments: sitepoint.com/deploy-cakephp-apps-on-appfog-the-right-way
5

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;
        }
    }
}

1 Comment

IN cake 1.3 it does not work. Cake returns sql errors" SQL Error: 1064: You have an error in your SQL syntax;"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.