はじめに
案件の都合により、
複数サブドメイン下で、Config, Helper, Model を共通で使いたい
という状況になり、方法を調べた結果です。
他に素晴らしい方法があれば、そちらを採用していただいたうえ教えてください。
やりたいこと
次のようなサブドメイン構成だとします。
http://subdomain1.hoge.com/
http://subdomain2.hoge.com/
http://subdomain3.hoge.com/
サブドメインごとに表示内容を変えるが、同じデータベースを使うので Config や Model は流用したい。
そこで、
サブドメインごとに webroot を作り、webroot/index.php で何とかしよう
という考え方のもと、このようなディレクトリー構成にしました。
cakephp /app /lib /plugins /subdomain /subdomain1 /Controller /View /webroot /subdomain2 ※subdomain1と同じ /subdomain3 ※subdomain1と同じ
公開ディレクトリーについて
通常、CakePHP で構成されたサイトを公開するさい
cakephp cakephp/app/webroot
以上のいずれかを公開ディレクトリーとして WEBサーバーに登録できます。
今回、 一つの CakePHP で複数サブドメインの処理をさせるのが目的なので、ドメインとディレクトリーの関係は次のようになります。
ドメイン | 公開パス |
---|---|
http://subdomain1.hoge.com | cakephp/subdomain1/webroot |
http://subdomain2.hoge.com | cakephp/subdomain2/webroot |
http://subdomain3.hoge.com | cakephp/subdomain3/webroot |
webroot/index.php の変更
app ディレクトリーの指定変更
webroot/index.php のパスを元に、 cakephp ディレクトリーのパスを取得し ROOT として設定します。
/** * The full path to the directory which holds "app", WITHOUT a trailing DS. * */ if (!defined('ROOT')) { define('ROOT', dirname(dirname(dirname(dirname(__FILE__))))); }
Controller, View ディレクトリーの指定
App::build 関数で Controller, View のパスを追加/削除/初期化できます。
App::build(array('Controller' => array(ROOT . DS . 'subdomain' . DS . 'subdomain1' . DS . 'Controller' . DS))); App::build(array('View' => array(ROOT . DS . 'subdomain' . DS . 'subdomain1' . DS . 'View' . DS)));
App::build() を使うことで、サブドメインどうこうが関係なくてもディレクトリー指定/追加の自由度があるので、都合によって使っていきましょう。
以上、 subdomain2, subdomain3 にも同じ変更を行えば完了です。