設定ファイルの操作

あらゆるアプリケーションはその設定を行う変数の定義方法を必要とします。 設定ファイルを通して制御を行います。設定ファイルにはシンプルにクラスを置いてあり、public プロパティで設定します。多くのフレームワークとは異なり、設定値にアクセスするための特定のクラスはありません。代わりに、設定ファイルのクラスのインスタンスを作ることで設定値を用意します。

設定ファイルへのアクセス

あなたのクラス内で設定ファイルにアクセスするには、新しいインスタンスを作るか config 関数を使います。すべてのプロパティは public です。他のプロパティ同様に設定値にアクセスできます:

// 手動でクラスを new します
$config = new \Config\Pager();

// config 関数で新しくクラスを生成します
$config = config( 'Pager', false );

// config 関数で共有インスタンスを取得します
$config = config( 'Pager' );

// 名前空間を使って設定クラスにアクセスします
$config = config( 'Config\\Pager' );

// クラスのプロパティとして設定にアクセスします
$pageSize = $config->perPage;

名前空間が提供されない場合、定義されているすべての利用可能な名前空間のファイルを探しに行きます。もちろん /app/Config/ もです。CodeIgniter が提供している設定ファイルはすべて名前空間 Config になっています。名前空間を利用することはアプリケーションのパフォーマンスを最適にします。どのディレクトリにファイルを探しに行けばよいかを正確に示し、ファイルシステムのいろんな場所をスキャンせずに済ませられるからです。

違う名前空間を使用することで、サーバのあらゆる場所に設定ファイルを配置することもできます。 この機能は、本番サーバ上では web アクセスできない場所から設定ファイルを読み込みつつ、開発環境では /app を容易にアクセスできる場所に置いておくことを可能にします。

設定ファイルの作成

新たな設定ファイルを作りたい場合、好きな場所に作ることもできますが、/app/Config がデフォルトです。クラスを作成して、public プロパティを代表的な設定値で埋めてください:

<?php namespace Config;

use CodeIgniter\Config\BaseConfig;

class App extends BaseConfig
{
    public $siteName  = '我が偉大なるサイト';
    public $siteEmail = 'webmaster@example.com';

}

設定クラスは \CodeIgniter\Config\BaseConfig を継承する必要があります。環境ごとの設定を受け付けられるようにするためです。

環境ごとの違いの制御

開発者のローカルマシンと本番サイトのサーバのような、複数の環境で操作するために、環境に基づいた値を設定することができます。動作するサーバに依存して変更すべき設定はこれらの中にします。これはデータベース設定、 API 証明書、その他デプロイ間で変わる設定を含めることができます。

ルートディレクトリの .env ファイル内に値を格納しておくことができ、 system や application ディレクトリと横並びになります。 等号で区分けされた名前と値のシンプルな集合で、 ".ini" ファイルによく似ているものです:

S3_BUCKET="dotenv"
SECRET_KEY="super_secret_key"

環境変数にすでに設定されている変数の場合、上書き さ れ ま せ ん 。

重要

.env ファイルを .gitignore (またはあなたの版数管理システムの同等物)に加えてあることを確認してください。コードにチェックインされないように。それをミスれば、機微情報である認証情報がリポジトリに保存されて余人の知るところとなるでしょう。

おすすめはテンプレートファイルを作ることです、 env.example のような。あなたのプロジェクトで必要となる全変数を空の値ないしダミーデータとしておきます。それぞれの環境では、そのファイルを .env にコピーして、適切な値を埋めます。

アプリケーションが実行されるとき、このファイルは自動的に読み込まれて環境に設定されます。これはあらゆる環境で動作します。これらの変数は getenv()$_SERVER 、 そして $_ENV で利用可能です。3つの中では、 getenv() 関数が推奨されます。大文字小文字を区別しないからです:

$s3_bucket = getenv('S3_BUCKET');
$s3_bucket = $_ENV['S3_BUCKET'];
$s3_bucket = $_SERVER['S3_BUCKET'];

注釈

Apache を使っている場合、 CI_ENVIRONMENT は public/.htaccess の先頭に位置しているかもしれません、そのようにコメント行があります。使いたい値に書き換えて、コメントを外してください。

入れ子変数

タイピングの省力化のため、ファイル内で指定済の変数は再利用できます。変数名を ${...} で囲ってください:

BASE_DIR="/var/webroot/project-root"
CACHE_DIR="${BASE_DIR}/cache"
TMP_DIR="${BASE_DIR}/tmp"

Namespaced Variables

There will be times when you will have several variables with the same name. When this happens, the system has no way of knowing what the correct value should be. You can protect against this by "namespacing" the variables.

Namespaced variables use a dot notation to qualify variable names when those variables get incorporated into configuration files. This is done by including a distinguishing prefix, followed by a dot (.), and then the variable name itself:

// not namespaced variables
name = "George"
db=my_db

// namespaced variables
address.city = "Berlin"
address.country = "Germany"
frontend.db = sales
backend.db = admin
BackEnd.db = admin

Incorporating Environment Variables Into a Configuration

When you instantiate a configuration file, any namespaced environment variables are considered for merging into the configuration objects' properties.

If the prefix of a namespaced variable matches the configuration class name exactly, case-sensitive, then the trailing part of the variable name (after the dot) is treated as a configuration property name. If it matches an existing configuration property, the environment variable's value will override the corresponding one in the configuration file. If there is no match, the configuration properties are left unchanged.

The same holds for a "short prefix", which is the name given to the case when the environment variable prefix matches the configuration class name converted to lower case.

Treating Environment Variables as Arrays

A namespaced environment variable can be further treated as an array. If the prefix matches the configuration class, then the remainder of the environment variable name is treated as an array reference if it also contains a dot:

// regular namespaced variable
SimpleConfig.name = George

// array namespaced variables
SimpleConfig.address.city = "Berlin"
SimpleConfig.address.country = "Germany"

If this was referring to a SimpleConfig configuration object, the above example would be treated as:

$address['city']    = "Berlin";
$address['country'] = "Germany";

Any other elements of the $address property would be unchanged.

You can also use the array property name as a prefix. If the environment file held instead:

// array namespaced variables
SimpleConfig.address.city = "Berlin"
address.country = "Germany"

then the result would be the same as above.

Registrars

A configuration file can also specify any number of "registrars", which are any other classes which might provide additional configuration properties. This is done by adding a registrars property to your configuration file, holding an array of the names of candidate registrars.:

protected $registrars = [
    SupportingPackageRegistrar::class
];

In order to act as a "registrar" the classes so identified must have a static function named the same as the configuration class, and it should return an associative array of property settings.

When your configuration object is instantiated, it will loop over the designated classes in $registrars. For each of these classes, which contains a method name matching the configuration class, it will invoke that method, and incorporate any returned properties the same way as described for namespaced variables.

A sample configuration class setup for this:

<?php namespace App\Config;

use CodeIgniter\Config\BaseConfig;

class MySalesConfig extends BaseConfig
{
    public $target        = 100;
    public $campaign      = "Winter Wonderland";
    protected $registrars = [
        '\App\Models\RegionalSales';
    ];
}

... and the associated regional sales model might look like:

<?php namespace App\Models;

class RegionalSales
{
    public static function MySalesConfig()
    {
        return ['target' => 45, 'actual' => 72];
    }
}

With the above example, when MySalesConfig is instantiated, it will end up with the two properties declared, but the value of the $target property will be over-ridden by treating RegionalSalesModel as a "registrar". The resulting configuration properties:

$target   = 45;
$campaign = "Winter Wonderland";