Yii2 params 在公共目录中的本地配置文件中访问 [英] Yii2 params access within local config file in common directory
问题描述
我正在使用 Yii2
高级模板,我想访问 main-local.php
文件中的 params.php
,我这样称呼:
main-local.php:
'mailer' =>['类' =>'我的课','apikey' =>\Yii::$app->params['mandrill_api_key'],'视图路径' =>'@common/mail',],
并且我已经将这个 mandrill_api_key
存储在 params.php
params.php:
'admin@example.com','supportEmail' =>'support@example.com','user.passwordResetTokenExpire' =>3600,'mandrill_api_key' =>'我的钥匙'];
我收到此错误:
<块引用>注意:第 25 行试图在 C:\xampp\htdocs\myproject\common\config\main-local.php 中获取非对象的属性
我应该怎么做才能访问这些参数?
在应用程序实例化之前读取配置文件,如 请求生命周期:
<块引用>- 用户向入口脚本 web/index.php 发出请求.
- 入口脚本加载应用程序配置并创建一个应用程序实例来处理请求.
- 应用程序在请求应用程序组件的帮助下解析请求的路由.
- ...
因此 \Yii::$app
尚不存在,因此出现错误.我建议将您的 api_key 定义移动到 main-local.php
配置,这样就不会混淆它的设置位置:
'mailer' =>['类' =>'我的课','apikey' =>'实际的 api 密钥','视图路径' =>'@common/mail',],
或者,您可以使用 Yii2 的 依赖注入容器 在应用程序的入口脚本中设置 apikey
:
<代码>...$app = new yii\web\Application($config);\Yii::$container->set('\fully\qualified\myClass', ['apikey' =>\Yii::$app->params['mandrill_api_key'],]);$app->run();
I'm using Yii2
advanced template,
I want to access params.php
in main-local.php
file,
I called this ways:
main-local.php:
'mailer' => [
'class' => 'myClass',
'apikey' => \Yii::$app->params['mandrill_api_key'],
'viewPath' => '@common/mail',
],
and I have stored this mandrill_api_key
in params.php
params.php:
<?php
return [
'adminEmail' => 'admin@example.com',
'supportEmail' => 'support@example.com',
'user.passwordResetTokenExpire' => 3600,
'mandrill_api_key' => 'mykey'
];
I'm getting this error:
Notice: Trying to get property of non-object in C:\xampp\htdocs\myproject\common\config\main-local.php on line 25
What should I do to access these parameters?
The config files are read before the application is instantiated as explained in the request lifecycle:
- A user makes a request to the entry script web/index.php.
- The entry script loads the application configuration and creates an application instance to handle the request.
- The application resolves the requested route with the help of the request application component.
- ...
As such \Yii::$app
does not yet exist hence the error. I would suggest moving your api_key definition to the main-local.php
config such that there is no confusion over where it is being set:
'mailer' => [
'class' => 'myClass',
'apikey' => 'actual api key',
'viewPath' => '@common/mail',
],
Alternatively, you can use Yii2's dependancy injection container to set the apikey
in your application's entry script:
...
$app = new yii\web\Application($config);
\Yii::$container->set('\fully\qualified\myClass', [
'apikey' => \Yii::$app->params['mandrill_api_key'],
]);
$app->run();
这篇关于Yii2 params 在公共目录中的本地配置文件中访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!