您可以添加新的应用程序组件
class EConfig extends CApplicationComponent
{
public $cache = 0;
public $dependency = null;
protected $data = array();
public function init()
{
$items=Config::model()->findAll();
foreach ($items as $item)
{
if ($item['param'])
$this->data[$item['param']] = $item['value'] === '' ? $item['default'] : $item['value'];
}
parent::init();
}
public function get($key)
{
if (array_key_exists($key, $this->data))
return $this->data[$key];
else
//throw new CException('Undefined parameter ' . $key);
return '';
}
public function set($key, $value)
{
$model = Config::model()->findByAttributes(array('param'=>$key));
if (!$model)
throw new CException('Undefined parameter ' . $key);
$model->value = $value;
if ($model->save())
$this->data[$key] = $value;
}
public function add($params)
{
if (isset($params[0]) && is_array($params[0]))
{
foreach ($params as $item)
$this->createParameter($item);
}
elseif ($params)
$this->createParameter($params);
}
public function delete($key)
{
if (is_array($key))
{
foreach ($key as $item)
$this->removeParameter($item);
}
elseif ($key)
$this->removeParameter($key);
}
protected function getDbConnection()
{
if ($this->cache)
$db = Yii::app()->db->cache($this->cache, $this->dependency);
else
$db = Yii::app()->db;
return $db;
}
protected function createParameter($param)
{
if (!empty($param['param']))
{
$model = Config::model()->findByAttributes(array('param' => $param['param']));
if ($model === null)
$model = new Config();
$model->param = $param['param'];
$model->label = isset($param['label']) ? $param['label'] : $param['param'];
$model->value = isset($param['value']) ? $param['value'] : '';
$model->default = isset($param['default']) ? $param['default'] : '';
$model->type = isset($param['type']) ? $param['type'] : 'string';
$model->save();
}
}
protected function removeParameter($key)
{
if (!empty($key))
{
$model = Config::model()->findByAttributes(array('param'=>$key));
if ($model)
$model->delete();
}
}
}
之后,您可以使用它来将参数添加到数据库(如果还没有这样的参数)
Yii::app()->config->add(array(
'param' => 'PARAMNAME',
'label' => 'yourlabel',
'value' => 4534,
'type' => 'integer',
'default' => 4534,
));
获取参数值 -
Yii::app()->config->get('PARAMNAME');
设置参数值(如果参数存在)
Yii::app()->config->set('PARAMNAME',100500);
当然你需要为它创建表和类和控制器
CREATE TABLE `Config` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`param` varchar(128) NOT NULL,
`value` text NOT NULL,
`default` text NOT NULL,
`label` varchar(255) NOT NULL,
`type` varchar(128) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `param` (`param`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=290 ;
并对配置添加一些更改
components=>array(
...
'config' => array(
'class' => 'application.extensions.components.EConfig',
// 'cache'=>3600,
),
并将配置添加到配置中的预加载部分
'preload' => array(..,'config'),