Define global variable for Models and Controllers

2019-08-12 12:17发布

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.

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-12 12:53
  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();
查看更多
▲ chillily
3楼-- · 2019-08-12 13:10

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.

查看更多
登录 后发表回答