codeigniter中的多租户,通过子域选择了不同的数据库

问题描述 投票:0回答:1

我实际上是试图在Codeigniter中使用单个代码库和多个数据库来实现SaaS架构...

为清楚起见,请考虑以下示例:我有3个客户端,分别是client_1,client_2,client_3。我也有他们各自的数据库-client_1_db,client_2_db,client_3_db。

所以,我的问题是:将有三个带有子域的url,例如-www.client_1.localhost.com,www.client_2.localhost.com和www.client_3.localhost.com。当任何用户请求这些URL时,我必须选择他们各自的数据库以进行进一步处理。

我的项目正在使用codeigniter及其HMVC进行构建。

预先感谢..

php codeigniter subdomain saas hmvc
1个回答
0
投票
根据我的经验,您应该注意三件事。

首先是通配符子域,可以从任何子域访问您的应用程序(取决于您的主机/服务器设置)。>>

然后,您应该将不同的DB添加到config / database.php-> https://stackoverflow.com/a/8269596/953937

然后,您应该读取$ _SERVER ['HTTP_HOST']数据以获取子域,有了子域,您可以加载相应的DB ...在core / MY_Controller.php中应该是这样的

public function __construct() { parent::__construct(); // get subdomain $subdomain = explode('.', $_SERVER['HTTP_HOST'], 2); $subdomain = $subdomain[0]; // check in main DB if client exists... $this->db->from('table_of_clients')->where('slug', $subdomain); $query = $this->db->get(); if($query->num_rows() < 1) { header("Location: http://error.yourdomain.com"); } else { // load client DB $this->load->database($subdomain.'_db', TRUE); } }

未测试,希望它能起作用。

问候!

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.