LoginSignup
4
2

More than 3 years have passed since last update.

CakePHP config配下のディレクトリ内の設定ファイルを読み込む

Last updated at Posted at 2018-12-14

ディレクトリ構成

ディレクトリ構成
project
    |
    - bin
    - config
        |
        - Migrations
        - hoge
            |
            - huga.php
        - schema
        - Seeds
        app.default.php
        app.php
        bootstrap.php
        routes.php
    - logs
    - plugins
    - src
    - tests
    - tmp
    - vendor
    - webroot

前提

  • configディレクトリ配下に存在するhogeディレクトリ内のhuga.phpの設定を読み込む
  • bootstrap.phpにはConfigure::loadされている

読み込む

HogeController
<?php
namespace App\Controller;

use App\Controller\AppController;

class HogeController extends AppController
{
    public function index()
    {
        Configure::read('huga');
    }
}

HogeControllerで読み込みたい場合、この状態でConfigure::read()をしてもエラーになります。
理由としては、Configure::read()はconfigディレクトリ直下のファイルを参照するからです。

なので、HogeControllerの先頭でuse Cake\Core\Configure;をしてエイリアスを作成します。

ConfigureはCakePHPがもともと持つクラスです。
エイリアスを作成することで、config配下のディレクトリ内のファイルも参照することが出来るようになります。

HogeController
<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Core\Configure;

class HogeController extends AppController
{
    public function index()
    {
        Configure::read('huga');
    }
}

参考

https://book.cakephp.org/3.0/ja/development/configuration.html#namespace-Cake\Core
https://book.cakephp.org/3.0/ja/development/configuration.html#id3
https://remotestance.com/blog/3064/
http://blog.fagai.net/2015/01/18/cakephp3-configure-class/

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2