Define global variable for Models and Controllers at CakePHP 2.2

坚强是说给别人听的谎言 提交于 2019-12-11 09:43:37

问题


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.


回答1:


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.




回答2:


  1. create the getSettings in your AppModel
  2. in AppController you can write this method:

    public function getSettings() {
        return $this->{$this->modelClass}->getSettings();
    }
    

this way the getSettings() method is available in any model and any controller

any model call:

$mysettings = $this->getSettings();

any controller call:

$mysettings = $this->MODELNAME->getSettings();


来源:https://stackoverflow.com/questions/13140588/define-global-variable-for-models-and-controllers-at-cakephp-2-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!