Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - database config based on URL

Tags:

cakephp

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

like image 208
teepusink Avatar asked Jun 17 '11 07:06

teepusink


People also ask

How does CakePHP connect to multiple databases?

First open app/Config/database. php file in any code editor. The default database is public $default , if you want to use other database(db2, db3) you need to initialize new database in your Model using $useDbConfig predefined cakephp method see example.


2 Answers

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.

like image 200
JohnP Avatar answered Oct 15 '22 11:10

JohnP


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;
        }
    }
}
like image 37
Jankeesvw Avatar answered Oct 15 '22 09:10

Jankeesvw