1

Yiiでカスタム拡張機能を構築しようとしていますが、カスタム構成にアクセスできません。

main.phpに次のものがあるとします。

'my_extension'=>array(
    'class'=>'ext.my_extension.my_extension'
    'custom_config'=>array(
        'first_option'=>array(
            'active'=>true,
            'custom_username'=>'username',
            'custom_password'=>'password',
        ),
    ),
),

「active」、「custom_username」、「custom_password」にアクセスするにはどうすればよいですか?

CFormModelを拡張する私の拡張機能では、次のことを試しました。

Yii::app()->my_extension->custom_config['first_option']['custom_username'];

しかし、エラーが発生します:

Property "my_extension.custom_config" is not defined.
4

2 に答える 2

8

これがエラーになる理由は、配列で定義されている、宣言されていないYii :: app()のプロパティにアクセスしようとしているためです。

エントリースクリプト(index.php)は通常、このようなYiiオブジェクトを作成します。

require_once($yii);
Yii::createWebApplication($config)->run();

$ config変数はmain.configファイル配列であるため、Yii :: app()のプロパティと一致しないインデックスを配列に追加しても、それは作成されません。

カスタム設定を設定するために、Yiiは私たちにparams..として使用できるものを提供しますYii::app()->params['paramName']

したがって、あなたの場合は、config.mainの最後の「params」インデックスは次のようになります。

'params'=>array(
    'my_extension'=>array(
        'class'=>'ext.my_extension.my_extension',
        'custom_config'=>array(
            'first_option'=>array(
                'active'=>true,
                'custom_username'=>'username',
                'custom_password'=>'password',
            ),
        ),
    ),
    //...remaining params
),

使用法は

Yii::app()->params['my_extension']['custom_config']['first_option']['custom_username'];

編集:

yr拡張子の設定、またはfacebookやpostmarkのようなものを別々に設定する必要がある場合があります。これは、別々の環境に別々の値があり、そのファイルを入れたい.gitignore場合、またはyr拡張子を解放して開くために必要な場合があります。 -ソース、および人々が独自の構成を持つ明確な方法を提供することを望んでいます。

したがって、これらの場合の解決策は、yr extまたは任意の場所でファイルを作成し、構成値を含む配列を作成し、そのファイルをに含めindex.php、yrconfig/mainにそのコンテンツを配置することです。

あなたの場合:

//in index.php
require_once(dirname(__FILE__).'/protected/ext/yr_ext/ext_config.php');

//in ext/yr_ext/ext_config.php
<?php
class ExtConfiguration {
public static function fetchConfigArray() {
        return array(
        'class'=>'ext.my_extension.my_extension',
                'custom_config'=>array(
                    'first_option'=>array(
                        'active'=>true,
                        'custom_username'=>'username',
                        'custom_password'=>'password',
                    ),
                ),
            );
    }
}
?>

//in config/main.php
//on top before array start
$ext_config = ExtConfiguration::fetchConfigArray();

//in params
'params'=>array(
    'my_extension'=>$ext_config,
),
//...remaining params
于 2012-07-11T18:11:19.140 に答える
1

共有したconfigフラグメントによって、メインクラスでパブリックプロパティを定義する必要があるとおっしゃいました$custom_config

そして単にあなたはあなたの拡張機能のように$this->custom_config

于 2012-07-11T17:51:24.883 に答える