【发布时间】:2014-09-11 19:02:19
【问题描述】:
我正在尝试根据谁尝试登录我的页面来更改我的数据库连接。
我需要一种方法来保存正确的数据库名称,以便我的所有控制器都可以访问它。
使用会话会起作用,但我怀疑它的安全性和/或良好做法。 如果我可以从我的 AccountsController 在 AppController 中设置一个变量,那将是完美的。但基本上任何能让我在所有控制器之间共享变量的方式。
在我的 AccountsController 中,我在标准数据库中查询正确的名称。然后我使用configure::write('CompanyDB', $myDbVar)。这个控制器工作正常,但我不能在任何其他控制器中使用configure::read('CompanyDB')。
在我的 AppModel 中,我有一个构造函数,它根据前面提到的 configure::read('campanyDB') 中的值设置数据库连接,我需要在我的所有控制器中使用 configure::write('CompanyDB',$myDbVar) 才能工作。
在我的帐户模型中,我设置了$specific=true。这告诉 AppModel 它应该使用该构造并更改数据库连接。
class AccountsController extends AppController {
public $helpers = array('Html', 'Form','Js');
public $components = array('RequestHandler');
var $uses = array('User', 'Company');
public $name = 'Accounts';
public $myDbVar='coolbeans';
public function beforeFilter() {
parent::beforeFilter();
Configure::write( 'companyDB',$this->myDbVar);
}
}
class AppModel extends Model {
var $specific = false;
function __construct($id = false, $table = null, $ds = null) {
if ($this->specific) {
// Get saved company/database name
$dbName = Configure::read('companyDB');
// Get common company-specific config (default settings in database.php)
$config = ConnectionManager::getDataSource('companySpecific')->config;
// Set correct database name
$config['database'] = $dbName;
// Add new config to registry
ConnectionManager::drop('companySpecific');
ConnectionManager::create('companySpecific', $config);
// Point model to new config
$this->useDbConfig = 'companySpecific';
}
parent::__construct($id, $table, $ds);
}
}
class Account extends AppModel {
public $primaryKey = '_id';
//var $useDbConfig = 'mongo';
var $specific = true;
.....
}
【问题讨论】:
标签: php cakephp global-variables