Yii 1.1: settings

Another way to store configuration items to database

This extension is an alternative to my "myconfig" extension from here: http://www.yiiframework.com/extension/myconfig/ but it uses only the database+caching.

As explained in this comment http://www.yiiframework.com/extension/myconfig/#c3727 using this extension has some advantages and some extra requirements.


1) Yii 1.1.x
2) A Cache component activated (CFileCache will do it just fine)


Add the component to the main.php config file:

        'class'                 => 'CmsSettings',
        'cacheComponentId'  => 'cache',
        'cacheId'           => 'global_website_settings',
        'cacheTime'         => 84000,
        'tableName'     => '{{settings}}',
        'dbComponentId'     => 'db',
        'createTable'       => true,
        'dbEngine'      => 'InnoDB',


* Set a database item:  
* $itemName can be an associative array() in key=>value pairs  ($itemValue="" in this case) 
Yii::app()->settings->set($categoryName, $itemName, $itemValue, $toDatabase=true);  
// Get a database item:  
Yii::app()->settings->get($categoryName, $itemName);  
// Get all items from a category:  
// Delete a database item:  
Yii::app()->settings->delete($categoryName, $itemName);  
// Delete all items from a category:  
//Import items from a file:  
$items=include('path/to/file.php');//returns an array() in key=>value pairs  
Yii::app()->settings->set($categoryName, $items);

The component uses something like "lazy loading" for loading items within a category, meaning that the items from a category will be loaded when you request them first time. Beside this, at the end of the request, the items from that requested category are written to cache, so next time when you request them, they will be served from cache.

Note, the component is smart enough to know itself when a new item/category has been added and refresh the cache accordingly so you don't have to keep track of the items you add to database.

Basically, in most of the cases, the database will be hit only once, then all items will be served from cache, which means you will get a nice way to manage the project configuration without performance penalties.

Notes & Changelog

Version 1.1.c
Various improvements

Version 1.1.d
-> Contains small performance improvements.
-> You can now use the get() method like

$retrieve_custom_settings=Yii::app()->settings->get('system',array('admin_email','contact_email','my_email'=>'some default value'));

In the above example, $retrieve_custom_settings becomes an array having the 'admin_email' and 'contact_email' keys. If these values are empty or they don't exists in database then they will be set to null otherwise you will retrieve their values. It is set this way so that you can safely use $retrieve_custom_settings['admin_email'] even if it doesn't exists.

Version 1.1.e
->Added setters/getters for all the public properties.
->The component supports the automatic creation of the database table (optionally, you can specify which storage engine to use in case you use MYSQL)
->Added the option to specify the name of the Cache/Database components via the $cacheComponentId and $dbComponentId properties.
->removed the __call() magic function.
->commented the class methods.

Special thanks goes to Gustavo who helped me allot with this version.

Upgrading to this version will not break the backward compatibility in any way(hope you didn't make use of the __call() method) and it is recommended to do so.
In case you use the autocreate database table option, don't forget to turn it off after the table has been created.

Version 1.2
-> added the deleteCache() public method to allow to delete cached categories
-> implemented a cache registry that will hold all the cached categories and it will be updated each time a new category is loaded/deleted Usage:
-> various changes that won't break BC.

Yii::app()->settings->deleteCache('categoryName'); //delete a single category  
Yii::app()->settings->deleteCache(array('c1', 'c2','c3')); // delete multiple categories  
Yii::app()->settings->deleteCache(); // delete all cached categories.

Please let me know in case you find any error.

Total 20 comments

#19745 report it
Headshaker at 2016/01/18 05:07am
Yii 2 - Settings


As I've jumped from Yii to Yii 2 now, I decided to rewrite this extension for Yii 2.

You can find it here -> https://packagist.org/packages/marsoltys/yii2-settings

I've hope you will find it usefull.

#19673 report it
Hipogea at 2015/11/21 12:58pm

Something to keep in mind when use this extension , be very careful when you use transactions, ROLLBACK doesn' t work . I realized this after several hours to detect the inconsistency , please Documentation should warn of this, we would save much time.

In fact you must put the value False in te parameter 'createTable'

'createTable' => false,
In your config/main FILE

So you avoid troubles with ROLLBACK sentences

#19666 report it
Scott_Huang at 2015/11/16 09:52pm
Do you have time to upgrade settings to Yii2 version? Thanks.

This is a good widget. Do you have time to upgrade it to Yii2 version? Thanks.

#18395 report it
badi at 2014/10/23 11:21am
Database access

It seems its a realy good extension, but does it work with postgresql database? I tried to use it, but a lot of errors comes up depending on the components code.

#18183 report it
yiqing95 at 2014/09/23 04:54am
any play for yii2

this is a great extension . so it 's meaningful to rewriting for yii2 .

#17941 report it
paskuale at 2014/08/13 07:25am
tableprefix issue

Hi, in the config must point out that you do not want to make use of the prefix

            'connectionString' => 'mysql:host=localhost;dbname=dbname',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
                        'tablePrefix'  => '',
#17939 report it
paskuale at 2014/08/13 06:46am

HI, but the table {{settings}} it dynamically creates or is to be created manually? I see, dynamically ... and the fields manually right ?

#10271 report it
twisted1919 at 2012/10/16 06:17pm
Sorry, but not enough time right now :(

Hi all, i read all your comments but for now i don't really have enough time to implement everything as i am very busy at work. Hope i'll have some spare time to improve the extension in the near future(the version used in my projects already is better, so i'll post all at once).
Thanks for your pacience:)

#10268 report it
yugene at 2012/10/16 04:57am
Approach to usage with many parameters

Hi to all,

This extension is very useful and I use it in several projects. From my experience, when application has a lot of different parameters, it may become not handy to manage them.

With following approach I'm trying to solve such hassles:

1) a lot of editions when you need to add new parameters to your application

2) obtrusive (not handy) code in model, controller and view files (which I first met on a large project where this extension was used)

3) instead of writing long requests, to use small helper function to call parameters

What can be improved:

1) add proper validation method (which isn't difficult to add, I just didn't need it for now)

2) get rid of literals usage as categories and parameters names - I think it would be more handy to have kinda of constants.

Your suggestions are welcome :)


class SettingsController extends Controller
    public function actionIndex()
        $settings = app()->settings;
        $model = new SettingsForm();
        if (isset($_POST['SettingsForm'])) {
            foreach($model->attributes as $category => $values){
                $settings->set($category, $values);
            user()->setFlash('success', 'Site settings were updated.');
        foreach($model->attributes as $category => $values){
            $cat = $model->$category;
            foreach($values as $key=>$val){
                $cat[$key] = $settings->get($category, $key);
            $model->$category = $cat;
        $this->render('index', array('model' => $model));


class SettingsForm extends CFormModel
    public $site = array(
        'name' => '',
        'googleAPIKey' => '',
        'numSearchResults' => '',
        'defaultLanguage' => '',
        'defaultCurrency' => '',
    public $seo = array(
        'mainTitle' => '',
        'mainKwrds' => '',
        'mainDescr' => ''
    public $mail = array(
        'adminEmail' => '',
        'fromReply' => '',
        'fromNoReply' => '',
        'server' => '',
        'port' => '',
        'user' => '',
        'password' => '',
        'ssl' => '',
    public $filter = array(
     * Declares customized attribute labels.
     * If not declared here, an attribute would have a label that is
     * the same as its name with the first letter in upper case.
    public function getAttributesLabels($key)
        $keys = array(
            'googleAPIKey' => 'Google API Key',
            'numSearchResults' => 'Number of search results at one page',
            'mainTitle' => 'Main Page Title',
            'mainKwrds' => 'Default Keywords (Meta Tag)',
            'mainDescr' => 'Default Description (Meta Tag)',
        if(array_key_exists($key, $keys))
            return $keys[$key];
        $label = trim(strtolower(str_replace(array('-', '_'), ' ', preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $key))));
        $label = preg_replace('/\s+/', ' ', $label);
        if (strcasecmp(substr($label, -3), ' id') === 0)
            $label = substr($label, 0, -3);
        return ucwords($label);
     * Sets attribues values
     * @param array $values
     * @param boolean $safeOnly
    public function setAttributes($values,$safeOnly=true) 
        foreach($values as $category=>$values) 
            if(isset($this->$category)) {
                $cat = $this->$category;
                foreach ($values as $key => $value) {
                        $cat[$key] = $value;
                $this->$category = $cat;

views to set params

main view shows tabs, content for which is stored in partial views


<h3>Site Settings</h3>
<?php echo CHtml::errorSummary($model); ?>
echo CHtml::beginForm();
<ul class="nav nav-tabs" id="site-settings">
$tabs = array();
$i = 0;
    foreach ($model->attributes as $category => $values):?>
        <li<?php echo !$i?' class="active"':''?>><a href="#<?php echo $category?>" data-toggle="tab"><?php echo ucfirst($category)?></a></li>
    $i ++;
    <div class="tab-content">
        $i = 0;
        foreach ($model->attributes as $category => $values):?>
            <div class="tab-pane<?php echo !$i?' active':''?>" id="<?php echo $category?>">
                        array('model' => $model, 'values' => $values, 'category' => $category)
        $i ++;
echo CHtml::submitButton('Submit', array('class' => 'btn'));
echo CHtml::endForm();

example partial view

<?php foreach ($values as $key => $val): ?>
    <div class="control-group">
        <?php echo CHtml::label($model->getAttributesLabels($key), $key); ?>
        if($key === 'ssl')
            echo CHtml::checkBox(get_class($model) . '[' . $category . '][' . $key . ']', $val); 
            echo CHtml::textField(get_class($model) . '[' . $category . '][' . $key . ']', $val, array('class'=>'input-xxlarge')); 
        <?php echo CHtml::error($model, $category); ?>
<?php endforeach; ?>

catch parameter

Helper function is stored in globals.php, which may be included to code in application bootstrap file.

 * Shortcut for Yii::app()->settings->get();
 * @param string $param 
function sg($category, $key){
    return Yii::app()->settings->get($category, $key);


sg('site', 'name');

P.S. I would put this message to extension forum topic but couldn't find the link to it here.

#9974 report it
dinhtrung at 2012/09/26 04:42am
Change createTable to Yii style

Hi, after using your settings for a long time, I see some minor fix should be made:

    protected function createTable()
        $schema = Yii::app()->getDb()->getSchema();
        $table = $schema->quoteTableName($this->getTableName());
        $create = $schema->createTable(
                'category' => 'string',
                'key'   =>  'string',
                'value' => 'text',
        $index = $schema->createIndex('category_key', $table, 'category,key', TRUE);
        return TRUE;

This will use Yii createTable instead of raw SQL one.

I think this is more convenient, in case switching db engine.

Also, remove the dbEngine variable, and table prefix. No need for that, right?

#9800 report it
twisted1919 at 2012/09/11 10:26am
will do

okay, this will be implemented in the next version (along with a few bug fixes) which will be available somewhere this week.

#9798 report it
fad at 2012/09/11 08:07am
Options to set table column names and default category name

Back to comment #4225 Nothing new, just new options. Question to author: Where to send the updated code, if possibly?

Or maybe I do fork on github?

protected $_dbComponentId='db';
    protected $_tableName='{{settings}}';
    protected $_idColumn='id';
    protected $_categoryColumn='category';
    protected $_keyColumn='key';
    protected $_valueColumn='value';
    protected $_createTable=false;
    protected $_dbEngine='InnoDB';
    protected $_defaultCategory='system';
    protected function createTable()
        $tableName=$connection->tablePrefix.str_replace(array('{{','}}'), '', $this->getTableName());
        $sql='CREATE TABLE IF NOT EXISTS `'.$tableName.'` (
          `'.$this->_idColumn.'` int(11) NOT NULL auto_increment,
          `'.$this->_categoryColumn.'` varchar(64) NOT NULL default \''.$this->_defaultCategory.'\',
          `'.$this->_keyColumn.'` varchar(255) NOT NULL,
          `'.$this->_valueColumn.'` text NOT NULL,
          PRIMARY KEY  (`'.$this->_idColumn.'`),
          KEY `'.$this->_categoryColumn.'_key` (`'.$this->_categoryColumn.'`,`'.$this->_keyColumn.'`)
        ) '.($this->getDbEngine() ? 'ENGINE='.$this->getDbEngine() : '').'  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; ';
#8420 report it
seb7 at 2012/06/01 09:56am
table name format

Ok, i don't use prefix.

I suggest writing it to the extension description text, because i hav'nt read all the comments (but maybe i'm the only one not reading all comments).


(Feel free to delete that comment and the previous one (if you can))

#8419 report it
twisted1919 at 2012/06/01 09:44am
database table prefix

it was written somewhere here that your database settings should also include a database table prefix even if it is just an empty string .

#8418 report it
seb7 at 2012/06/01 09:39am
db design

I'm not a db expert, but it looks like the database table field 'id' is not used for insert/update/delete operation, so the primary key (id) of that table is not used. It could be better to have a composite primary key ('category','key').

#8417 report it
seb7 at 2012/06/01 09:32am
table name format

I had to remove the {{ }} around the table name param (in config file or in the default param value. To get it to work.

Otherwise it raise an exception :

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{settings}} WHERE `category`='bidon' AND `key`='appname' LIMIT 1' at line 1. The SQL statement executed was: SELECT id FROM {{settings}} WHERE `category`=:cat AND `key`=:key LIMIT 1 

Then it seems to work ok (not tested a lot).

2012-06-01 17:24:39 Apache/2.2.21 (FreeBSD) mod_ssl/2.2.21 OpenSSL/0.9.8q PHP/5.3.8 with Suhosin-Patch Yii Framework/1.1.10

#6022 report it
twisted1919 at 2011/12/06 08:06am
Component updated.

The component has been updated to version 1.2 with some new goodies (see changelog) Please test it and report any bug you find. Thanks.

#6019 report it
twisted1919 at 2011/12/06 05:37am
Clear cache

This would require to have some kind of registry to store permanently all the defined categories that are cached, and it might be a good thing to have something like:

Yii::app()->settings->clearCache(); //clear all the cached content  
Yii::app()->settings->clearCache('category'); // clear only this category cache.

So i'll take it into consideration and implement it :)

#5958 report it
Pentium10 at 2011/11/30 03:12am
How to clear cache?

Can we have a method where clear the cache for all groups? (I have a migration that inserts some values into the settings table, and I would like to call a method after that to clear the cache.)

#4911 report it
twisted1919 at 2011/08/28 06:39am
Topic created

I opened a new topic here: http://www.yiiframework.com/forum/index.php?/topic/23075-extensionsettings/ , please add the file as an attachment there and i'll check it and in the end implement your changes.

Leave a comment

Please to leave your comment.

Create extension