multi tenant architecture

How would i build a multi tenant architecture using YII?

I have a database. all tables have a tenant_id which identifies/segregates data to a single tenant.

example: … projects table (id, name, tenant_id)

my approach, (pseudo code)

On login, set session(tenant) to user.tenant_id.

When display data, select data where tenant = session variable.

on insert/update, delete, get user.tenant (make sure it is the correct tenant), then do action.

questions:

  1. is session variable a viable choice? session variable is unstable in my experience.

  2. how can i set session variable condition (as in default scope) once and not in every single model?

  3. any other way that would make this easier/more secure? What are you doing?

This is what defaultScope is made for. Read some of my posts on this topic for more information.

Make a base model with a defaultScope. Inherit from this model when you want the scope, don’t inherit from it when you don’t. Or, disable the defaultScope as needed.