Skip to content

Instantly share code, notes, and snippets.

@UchePhilz
Last active April 28, 2019 17:30
Show Gist options
  • Save UchePhilz/9be7698f355578fc4099a9e5ff0aebd4 to your computer and use it in GitHub Desktop.
Save UchePhilz/9be7698f355578fc4099a9e5ff0aebd4 to your computer and use it in GitHub Desktop.
Php how to implement database multi-tenancy (YII2)
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace app\assets;
define("TENANT_SESSION_KEY", "tenant_session_key");
/**
* Description of TenancyAsset
*
* @author uchep
*/
class TenancyAsset {
/*
* How to enable tenancy
* Replace getDb() in the \yii\base\Application with the code below
*
* public function getDb() {
$b = $this->get('db');
$dbName = \app\assets\TenancyAsset::getDatabaseName();
$b->dsn = str_replace('db_name', $dbName, $b->dsn);
return $b;
}
*/
/**
* this function should get data of the merchant from the whatever service is provided
* @return type
*/
private static function getTenantLiveDetails() {
return['database_name' => 'cuorma'];
}
/**
* this set the merchant detail in the sesssion
* @param type $tenantDetails
*/
private static function setTenantSession($tenantDetails) {
\Yii::$app->session->set(TENANT_SESSION_KEY, $tenantDetails);
}
/**
* get merchant details from session
*
* @return type
*/
private static function getTenantSession() {
return \Yii::$app->session->get(TENANT_SESSION_KEY);
}
/**
*
* this functions gets the merchant data by returning the merchant detail from session of available
* if not, it will try to get the data from the service, if also not available, it throws NotFoundHttpException
*
* this function was created as a test of the DB tenancy architecture
*
* @return type
* @throws NotFoundHttpException
*/
public static function accessTenantData() {
$st = TenancyAsset::getTenantSession();
if (isset($st)) {
TenancyAsset::setTenantSession($st);
} else {
$st = TenancyAsset::getTenantLiveDetails();
if (isset($st)) {
TenancyAsset::setTenantSession($st);
} else {
throw new NotFoundHttpException('UNKNOWN MERCHANT');
}
}
return $st;
}
public static function getDatabaseName() {
$st = TenancyAsset::accessTenantData();
if (isset($st)) {
return $st['database_name'];
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment