'Multi Tenancy SAAS Application in Codeigniter4 [duplicate]
I am trying to build a multi tenancy saas Application using Codeigniter4. I want to setup individual database for each tanent's data and one global database for users.
I want application to automatically switch to tanent's database based on the tanent id of the logged in user. for this I have identified the tanents subdomain as follows in
app/config/constants.php
if(!defined('myHostName')){
$sd=explode(".",$_SERVER['HTTP_HOST']);
//define('myHostName', $host);
if($sd[0]=='localhost')
define('dbname', 'defaultdb');
else
define('dbname', $sd[0]);
These codes identify the subcomain and define the dbname as the name of subdomain if call is from subdomain. Then I have defined two database groups in app/config/database.php as follows.
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db_blog',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
public $data = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => myHostName,
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
This is working fine but Now I want the select database dynamically based on the folder on the domain e.g for
tenant 1 the baseurl will be https://example.com/tenant1
tenant 2 the baseurl will be https://example.com/tenant2
tenant 3 the baseurl will be https://example.com/tenant3
the problem here is that first segment (in this case tenant1/tenant2/tenant3) are identified as controller by the codeigniter4, I assume that there must be some method to identify the foldername on sites url
or solution may be similar to https://www.sandeeprajoria.in/2013/05/multi-tenancy-with-codeigniter.html
Solution 1:[1]
Well it seems that the 'https://stackoverflow.com/questions/65790279/how-to-set-dynamic-baseurl-on-app-config-app-php-using-codeigniter-4' has answer to my problem. I am not sure about the security concerns. I would request you to comment if you have any idea regarding security if we follow the steps of setting dynamic base url
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Inder Singh Thakur |
