Php 当用户登录时,如果我连接到另一个数据库,如何在配置类中存储数据库凭据
我正在开发一个webapp,当它打开且用户未登录时,默认设置应设置为连接到数据库:Php 当用户登录时,如果我连接到另一个数据库,如何在配置类中存储数据库凭据,php,database,class,architecture,static,Php,Database,Class,Architecture,Static,我正在开发一个webapp,当它打开且用户未登录时,默认设置应设置为连接到数据库:maindb,当用户登录时,用户应断开与maindb数据库的连接,并连接到他自己的数据库 我尝试在会话中使用if语句检查保存的customer\u host和customer,但PHP不允许我在类变量中执行此类操作 我的问题是: 我如何创建这样的功能,配置变量可以根据会话是否存在自行设置。(使用对静态变量的调用) 这种结构/架构适合我的情况吗(“良好实践” 类配置 { PS:我不是那个决定为每个客户创建不同数据库
maindb
,当用户登录时,用户应断开与maindb
数据库的连接,并连接到他自己的数据库
我尝试在会话中使用if语句检查保存的customer\u host
和customer
,但PHP不允许我在类变量中执行此类操作
我的问题是:
类配置
{
private $host;
private $user;
private $password;
private $dbname;
/*************/
/* METHODS */
/*************/
/**
* Get Database instance
*
*/
public static function getInstance()
{
if (!isset(self::$instance))
self::$instance = new Database();
return self::$instance;
}
/**
* Default Constructor
*
* 1. Instantiate Log class.
* 2. Creates the parameter array.
*/
private function __construct()
{
// Load defaults
$this->loadDefaults();
// INIT VARIABLES
$this->parameters = array();
// Connect with global vars.
$this->Connect($this->host, $this->user, $this->password, $this->dbname);
}
/**
*
* Method to load the object with the defaut settings
*
*/
private function loadDefaults() {
$this->user = Config::DB_USERNAME;
$this->password = Config::DB_PASSWORD;
$this->host = Config::$DB_HOST;
$this->dbname = Config::$DB_NAME;
}
如果您建议添加其他内容,请询问,我将在config类中进行编辑。
注意:登录后请重定向到其他页面
class Config {
static $DB_NAME_BEFORE_LOGIN = 'maindb';
static $DB_NAME_AFTER_LOGIN = 'own';
public static get_database(){
if(logged_in){
///do you logic and return the database name
self::$DB_NAME_AFTER_LOGIN;
}else{
//do your logic and return the database name
self::$DB_NAME_BEFORE_LOGIN;
}
}
}
在你的职责范围内
private function loadDefaults() {
$this->user = Config::DB_USERNAME;
$this->password = Config::DB_PASSWORD;
$this->host = Config::$DB_HOST;
$this->dbname = Config::get_database();
}
您需要为每个不同的环境扩展一个基本配置类。但是为什么不使用INI文件来代替和。更适合于此目的。@marekful我使用INI文件,但经过研究后,我认为这不是一个好的做法。我得到了用户数据(主机和数据库名)从我连接到的maindb表。因此,实际上,我不需要ini文件。如果我将其添加到登录函数中,并更改变量Config::set('customer','new_value',为什么不在登录和注销函数中执行此操作-它将适用于同一页面。如果我加载/重定向到其他页面,它是否会删除我刚才设置的内容?我已作为答案发布。请检查它是否有帮助
private function loadDefaults() {
$this->user = Config::DB_USERNAME;
$this->password = Config::DB_PASSWORD;
$this->host = Config::$DB_HOST;
$this->dbname = Config::get_database();
}