Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from params.php in Yii2

Tags:

php

yii2

I'm using Yii2 for my application. In params.php file I have defined an array like:

return ['setValue'=>100];

And I have include params.php in web.php:

<?php
$params = require(__DIR__ . '/params.php');
$config = [
    'params' => $params,
];
return $config;

And I am using another file header.php in views folder. So how can I get params array in header.php? I have used like \Yii::$app->params;, but it is not working.

like image 751
shanthi Jagadeesh Avatar asked Jan 25 '17 18:01

shanthi Jagadeesh


2 Answers

Be sure you have a proper config/main.php (this is a sample for a backend application using advanced template)

  <?php
    $params = array_merge(
        require(__DIR__ . '/../../common/config/params.php'),
        require(__DIR__ . '/../../common/config/params-local.php'),
        require(__DIR__ . '/params.php'),
        require(__DIR__ . '/params-local.php')
    );

    return [
        'id' => 'your-app-backend',
        'name' => 'Your APP Backend',
        'basePath' => dirname(__DIR__),
        'bootstrap' => ['log'],
        'controllerNamespace' => 'backend\controllers',
        'modules' => [],
        'components' => [
            'log' => [
                'traceLevel' => YII_DEBUG ? 3 : 0,
                'targets' => [
                    [
                        'class' => 'yii\log\FileTarget',
                        'levels' => ['error', 'warning'],
                    ],
                ],
            ],
            'errorHandler' => [
                'errorAction' => 'site/error',
            ],
        ],
        'params' => $params,
    ];

Assuming you have a param.php with

<?php
  return [
    'adminEmail' => '[email protected]',
 ];

you can get the param using yii::$app->params

Yii::$app->params['adminEmail'];

for printing use

echo Yii::$app->params['adminEmail'];
like image 191
ScaisEdge Avatar answered Nov 19 '22 00:11

ScaisEdge


You can access to one value with:

$value = Yii::$app->params['nameParameter'];

But, If you want to get the array

$values = Yii::$app->params;

You should be able to access all the properties defined in your config file which are integrated for use as "Yii::$app" attributes. In this case In this case the "params" attribute. :

According to the documentation http://www.yiiframework.com/doc-2.0/guide-structure-applications.html

like image 25
gabriel alejandro Rodriguez Avatar answered Nov 18 '22 23:11

gabriel alejandro Rodriguez