Search by

iguazoft / yii2-tenancy

dannyrios81

Row-level multi-tenancy for Yii2 ActiveRecord that fails closed: scoped queries and mass writes, immutable tenant column, subdomain resolution, a schema checker for CI and isolation assertions for tests.

Package info

github.com/dannyrios81/yii2-tenancy

Type:yii2-extension

pkg:composer/iguazoft/yii2-tenancy

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-11-19 15:10 UTC

This package is auto-updated.

Last update: 2026-11-19 15:19:01 UTC


README

tests Latest Stable Version Total Downloads PHP License

Row-level multi-tenancy for Yii2 ActiveRecord that fails closed. One database, a tenant_id column on every business table, and a base model that makes it hard to leak one customer's data to another.

Leer en español

class Invoice extends \iguazoft\tenancy\TenantActiveRecord {}

TenantContext::current()->set($tenantId);   // done for you by TenantFilter, from the subdomain

Invoice::find()->all();                     // only this tenant's invoices
Invoice::findOne($idOfAnotherTenant);       // null
Invoice::deleteAll(['status' => 'draft']);  // only this tenant's drafts
(new Invoice(['tenant_id' => 999]))->save();// saved with the current tenant, not 999

TenantContext::current()->clear();
Invoice::find()->count();                   // throws TenantContextMissing

Tested on SQLite, MySQL/MariaDB and PostgreSQL, PHP 8.1 to 8.4.

Why another tenancy package

Most row-level tenancy code adds a default where() and hopes nobody forgets it. This package closes the usual leaks:

Leak What happens here
A later where() replaces the tenant condition The condition is added in prepare(), right before the SQL is built, so nothing can remove it.
updateAll() / deleteAll() skip find() They are scoped too.
The client sends tenant_id in the request body It is overwritten with the current tenant on insert.
An update moves a row to another tenant TenantImmutable is thrown.
Code runs without a tenant (a job, a console command, a bug) Every read and write throws TenantContextMissing. Nothing returns all tenants by accident.
joinWith() / viaTable() read the joined table without a tenant filter They are rejected unless you opt in with allowUnscopedJoins().
findBySql() cannot be scoped It is rejected.
Someone adds a table and forgets the tenant column php yii tenancy/check fails in CI.
A model is not actually isolated assertTenantIsolation() proves it in one test.

Installation

composer require iguazoft/yii2-tenancy

1. Tenant models

Add a tenant_id column (NOT NULL, indexed) to every business table and extend TenantActiveRecord:

use iguazoft\tenancy\TenantActiveRecord;

class Invoice extends TenantActiveRecord
{
    public static function tableName()
    {
        return '{{%invoice}}';
    }

    public function getLines()
    {
        return $this->hasMany(InvoiceLine::class, ['invoice_id' => 'id']); // also a TenantActiveRecord
    }
}

Different column name or UUIDs? Override tenantAttribute(); ids can be integers or strings.

public static function tenantAttribute(): string
{
    return 'organization_id';
}

The tenants table itself is a plain ActiveRecord.

2. Set the tenant

Web: from the subdomain

// config/web.php
'components' => [
    'tenantResolver' => [
        'class' => \iguazoft\tenancy\web\SubdomainResolver::class,
        'baseDomain' => 'example.com',            // acme.example.com → tenant "acme"
        'tenantClass' => \app\models\Tenant::class,
        'subdomainAttribute' => 'subdomain',
    ],
],
// in a base controller
public function behaviors()
{
    return [
        'tenant' => [
            'class' => \iguazoft\tenancy\web\TenantFilter::class,
            // reject suspended tenants, expired plans...
            'check' => function ($tenantId, $tenant) {
                if ($tenant->status === 'suspended') {
                    throw new \yii\web\ForbiddenHttpException('This account is suspended.');
                }
            },
        ],
    ] + parent::behaviors();   // put it before authentication
}

Scopes: TenantFilter::SCOPE_TENANT (default, needs a tenant subdomain), SCOPE_ROOT (only the bare domain, for sign-up or landing pages) and SCOPE_ANY.

Resolving by header, path or JWT claim instead? Call TenantContext::current()->set($id, $tenant) from your own filter. For a custom lookup in the resolver, set finder:

'finder' => fn (string $subdomain) => ($t = Tenant::findOne(['slug' => $subdomain])) ? [$t->uuid, $t] : null,

Console, queues and tests

TenantContext::current()->runAs($tenantId, function () {
    Invoice::updateAll(['status' => 'overdue'], ['<', 'due_at', time()]);
});

runAs() restores the previous tenant even if the callback throws.

3. Cross-tenant work

Platform administration and reports sometimes need every tenant. Make it explicit:

Invoice::findAcrossTenants()->where(['status' => 'unpaid'])->count();

To change rows of a tenant, switch to it with runAs().

Joins

Invoice::find()->with('lines')->all();                  // safe: each relation query is scoped

Invoice::find()
    ->allowUnscopedJoins()                              // explicit opt-in
    ->innerJoinWith('lines', false)
    ->andWhere(['invoice_line.tenant_id' => TenantContext::current()->require()])
    ->all();

4. Check the schema in CI

// config/console.php
'controllerMap' => [
    'tenancy' => [
        'class' => \iguazoft\tenancy\console\TenancyController::class,
        'models' => ['app\models' => '@app/models'],
        'globalTables' => [
            'migration' => 'Yii migration history',
            'tenant' => 'The tenants themselves',
        ],
        // 'requireForeignKey' => true,
    ],
],
$ php yii tenancy/check
[tenancy] table audit_log has no model; add one that extends TenantActiveRecord or list the table as global
[tenancy] table note "org_id" is not the first column of any index

2 problem(s) found.

Every table must be a tenant table or be listed as global with a reason, so a new table cannot quietly skip isolation.

5. Prove isolation in tests

final class InvoiceIsolationTest extends \PHPUnit\Framework\TestCase
{
    use \iguazoft\tenancy\testing\IsolationAssertions;

    public function testInvoicesAreIsolated(): void
    {
        $this->assertTenantIsolation(
            Invoice::class,
            fn (array $attributes) => InvoiceFactory::create($attributes),
            tenantA: 1,
            tenantB: 2,
            mutation: ['status' => 'void'],
        );
    }
}

With two tenants seeded, it checks that tenant A cannot count, list, find, update or delete tenant B's rows, that inserts ignore a tenant sent by the client, that a row cannot move to another tenant, and that every operation fails without a tenant.

What it does not cover

  • Raw SQL through createCommand() or Query (not ActiveQuery) is not scoped. Keep it out of business tables.
  • batchInsert() and other Command helpers bypass the behavior.
  • Database-per-tenant or schema-per-tenant setups are out of scope.

Testing

composer install
composer test
# other databases
DB_DSN='mysql:host=127.0.0.1;dbname=tenancy' DB_USER=root DB_PASSWORD=secret composer test

License

MIT. See LICENSE.