iPhone/iPadのホーム画面コンテスト開催中!賞品は iTunes カード!

CakePHP & PHP 2006/09/17 03:28

CakePHP 環境に応じてDBの設定を変える

本番環境や開発環境など環境に応じてDBの設定を変える方法です。

1.AppModelを書き換える

withcakeで紹介されている方法です。

AppModelのコンストラクタで切り替えるアイデアは分かりやすくて良いと思います。ちなみに記事のコメントにもあったのですが、記事のコードだとコンストラクタの引数がModelへ渡されませんので、修正版を以下に書いておきます。

[app/app_model.php]

PHP:
  1. class AppModel extends Model {
  2.   function __construct($id = false, $table = null, $ds = null) {
  3.     $this->useDbConfig = $_SERVER['HTTP_HOST'] == 'devserver'?'test':'default';
  4.     parent::__construct($id, $table, $ds);
  5.   }
  6. }

2.database.phpを書き換える

NoswaDで紹介されている方法です。

cakebakerでも書かれていますが、database.phpは設定ファイルなので、これにコードを入れるのは若干抵抗を感じます。(まあdatabase.phpがなぜクラスになっているのか?という考えもありますが。)

3.Subversionで切り替える

cakebakerで紹介されている方法です。

I try to avoid to add code to configuration files because those files shouldn’t contain any logic. Instead I use Subversion to manage different configurations. In my repository I have at least two folders for each project: a “trunk” folder where the development happens, and a “live” folder which contains the code (and configurations) for the live application. So if I put something online I just export the content of the “live” folder from the repository, and with it the “live” configuration.

cakebaker » An alternative to “hacking” config files (2006-09-17)

「Subversion使えよ。なんでハックなんかやってるの?」と言ったところでしょうか。:)詳しい実践方法の記述が無いので的外れの可能性大ですが、これだとtrunk/とlive/でコードが別々になるような気がするのですが、どうなんでしょうか。

4.環境変数で切り替える

1.の変形版です。開発環境ではIPが変わる事があるので、環境変数で切り替える方法を考えてみました。これなら実行環境のIPがどうなろうと影響を受けません。

[httpd.conf]


SetEnv CAKE_DB_CONFIG test

[app/app_model.php]

PHP:
  1. <?php
  2. class AppModel extends Model {
  3.   function __construct($id = false, $table = null, $ds = null) {
  4.     $this->useDbConfig = empty($_SERVER['CAKE_DB_CONFIG']) ? 'default' : $_SERVER['CAKE_DB_CONFIG'];
  5.     parent::__construct($id, $table, $ds);
  6.   }
  7. }
  8. ?>

httpd.confで環境変数CAKE_DB_CONFIGを定義しておけば、その値をuseDbConfigに使用し、定義がなければ'default'を使用します。使い方としては本番環境が'default'で、開発環境等の他の環境は'dev'等を定義する形を考えています。



■Related Posts

  • No related posts

2 Responses to “CakePHP 環境に応じてDBの設定を変える”

  1. on 26 1月 2008 at 15:22 1.toyosystem | テスト環境から本番環境へのファイル適用 said …

    [...] CakePHP 環境に応じてDBの設定を変える | Shin x blog http://www.1×1.jp/blog/2006/09/cakephp_db_config.html [...]

  2. on 31 3月 2008 at 16:48 2.CakePHP 環境によってデータベースを切り替える | Sun Limited Mt. said …

    [...] CakePHP 環境に応じてDBの設定を変える | Shin x blog で色々な方法が紹介されています。 [...]

Trackback This Post | Subscribe to the comments through RSS Feed

Leave a Reply