Setting and getting systemwide static parameters

  1. The config file
  2. Sharing params between configs

Occasionally one wishes to set systemwide parameters for an application, such as a contact address for email, an application name, or setting an option that guides major behavior. Yii provides for setting of static parameters in the configuration file, and this article talks about how to do it conveniently.

The config file

In protected/config/main.php you'll find a 'params' attribute that can be populated with an array of name/value pairs:

return array(
    ...
    'params' => array(
        'email'      => 'steve@unixwiz.net',
        'someOption' => true
    )
)

These options are available at runtime via the Yii::app()->params[...] hash, which is indexed by the parameter name. And though it's possible to use it directly, it's prudent to check parameter existence first with isset(), so this makes it somewhat less convenient.

Our approach is to create a helper function to fetch these by name, with the caller providing a default value in the event the parameter is not set:

// in a helper file
function yiiparam($name, $default = null)
{
    if ( isset(Yii::app()->params[$name]) )
        return Yii::app()->params[$name];
    else
        return $default;
}

// in application code
$email      = yiiparam('email');             // null returned if not defined
$someOption = yiiparam('someOption', true);  // default to true if param not defined

This helper function can be placed in a common helper-function file as documented in this helpful wiki article; this is a great way to provide helper functions that your application needs often, but don't warrant a module, component, or special class.

Sharing params between configs

Users with console subsystems may well wish to share these parameters between main.php and config.php, and this can be done by creating a shared, common include file:

// in protected/config/_common.inc
$commonParams = array(
    'email'      => 'steve@unixwiz.net',
    'someOption' => true
);


// in protected/config/main.php
require_once('_common.inc');

return array(
    ...
    'params' => $commonParams
);


// in protected/config/console.php
require_once('_common.inc');

return array(
    ...
    'params' => $commonParams
);

Note that this method is for static configuration parameters - it's doesn't provide for dynamic parameters changed (or persisted) at runtime, or per-user settings.