Skip to content

ecommercebox/yii-multitenant

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Active Record MultiTenant Extension

This extension provides support for ActiveRecord MultiTenant.

Build Status Scrutinizer Code Quality Code Coverage Total Downloads Latest Stable Version

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist solutosoft/yii-multitenant

or add

"solutosoft/yii-multitenant": "*"

Usage

  1. Creates table with tenant_id column:
class m191023_101232_create_post extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function up()
    {
        $this->createTable('post', [
            'id' =>  $this->primaryKey(),
            'title' => $this->string()->notNull(),
            'category_id' => $this->integer(),
            'content' => $this->string()            
            'tenant_id' => $this->integer(),
        ]);
        
        $this->createTable('category', [
            'id' =>  $this->primaryKey(),
            'name' => $this->string()->notNull(),            
            'tenant_id' => $this->integer(),
        ]);
    }
}
  1. Adds TenantInterface to user model:
use solutosoft\multitenant\MultiTenantRecord;

class User extends MultiTenantRecord implements IdentityInterface, TenantInterface    
{
    /**
     * {@inheritdoc}
     */
    public function getTenantId()
    {
        return // logic to determine tenant from current user
    }
    
    /**
     * Finds user by username attribute
     * This is an example where tenant filter is disabled
     */
    public static function findByUsername($username)
    {
        return static::find()->withoutTenant()->where(['username' => $username]);
    }
    
    ...
    
}
  1. Extends models with tenant_id attribute from MultiTenantRecord intead of ActiveRecord:
use solutosoft\multitenant\MultiTenantRecord;

class Post extends MultiTenantRecord
{    
    ...   
}

class Category extends MultiTenantRecord
{    
    ...   
}

Now when you save or execute some query the tenant_id column will be used. Example:

// It's necessary the user will be logged in

$posts = \app\models\Post::find()->where(['category_id' => 1])->all();
// SELECT * FROM `post` WHERE `category_id` = 1 and `tenant_id` = 1;

$category = \app\models\Category([
  'name' => 'framework'
]);
$category->save();
// INSERT INTO `category` (`name`, `tenant_id`) values ('framework', 1);

About

Active Record MultiTenant Extension

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%