在CakePHP 2.2中为模型和控制器定义全局变量 [英] Define global variable for Models and Controllers at CakePHP 2.2
问题描述
目前我使用的是这样:
//在bootstrap.php文件
配置:: write ('from','mymail@mydomain.com')
//在控制器或模型文件
$ var = Configure :: read('from')
事情是,我想通过数据库管理这个变量,以便能够以更简单的方式修改它。 p>
我正在考虑用 AppModel
这样做,但是它只能被模型和控制器访问。
在这种情况下该怎么办?
谢谢。
您可以创建一个单独的模型/插件,它将映射到数据库中的配置表。然后通过控制器的 $ uses
语句和模型的 App :: import()
加载它。
class SystemSetting extends AppModel {
/ **
*返回所有设置的列表
*
* @access public
* @return array
* /
public function getSettings(){
return $ this-> find('all');
}
}
然后,在您的控制器中:
类SomeController扩展AppController {
var $ uses = array('SystemSetting');
public function displaySettings(){
$ settings = $ this-> SystemSetting-> getSettings();
// ..您的代码
}
}
模型:
App :: import('Model','SystemSettings.SystemSetting');
$ settings = new SystemSetting();
$ mySettings = $ settings-> getSettings();
这个很好。当然,您还可以在 AppController
和 AppModel
中加载设置,以遵循 DRY 规则。
Currently i am using something like this:
//at bootstrap.php file
Configure::write('from', 'mymail@mydomain.com')
//at controllers or models files
$var = Configure::read('from')
The thing is, i would like to manage that variable through the database to be able to modify it in a simpler way.
I was thinking about doing it with AppModel
but then it would only be accessible for Models and not controllers.
What should I do in this case?
Thanks.
You can create a separate model / plugin which will be mapped to a configuration table in your database. Then load it through $uses
statement for controllers and App::import()
for models.
class SystemSetting extends AppModel {
/**
* Return a list of all settings
*
* @access public
* @return array
*/
public function getSettings() {
return $this->find('all');
}
}
Then, in your controller:
class SomeController extends AppController {
var $uses = array('SystemSetting');
public function displaySettings() {
$settings = $this->SystemSetting->getSettings();
// .. your code
}
}
In model:
App::import('Model', 'SystemSettings.SystemSetting');
$settings = new SystemSetting();
$mySettings = $settings->getSettings();
This works just fine. Of course, you might also load settings in both AppController
and AppModel
to follow the DRY rule.
这篇关于在CakePHP 2.2中为模型和控制器定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!