toporia/tenancy 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

toporia/tenancy

Composer 安装命令:

composer require toporia/tenancy

包简介

Multi-tenancy support for Toporia Framework

README 文档

README

Multi-tenancy support for Toporia Framework.

Installation

composer require toporia/tenancy

Auto-Discovery

This package uses Toporia's Package Auto-Discovery system. After installation:

  • Service Provider is automatically registered - no manual registration required
  • Configuration is automatically discovered from extra.toporia.config in composer.json
  • Migrations are automatically included when running php console migrate

To rebuild the package manifest manually:

php console package:discover

Setup

Publish Config (optional)

php console vendor:publish --provider="Toporia\Tenancy\TenancyServiceProvider"
# Or with tag
php console vendor:publish --tag=tenancy-config

Or manually copy packages/tenancy/config/tenancy.php to config/tenancy.php.

Usage

1. Create Tenant Model

use Toporia\Tenancy\Contracts\TenantInterface;

class Tenant extends Model implements TenantInterface
{
    public function getTenantKey(): int|string
    {
        return $this->id;
    }

    public function getTenantIdentifier(): string
    {
        return $this->slug;
    }

    public function isActive(): bool
    {
        return $this->status === 'active';
    }
}

2. Add BelongsToTenant to Models

use Toporia\Tenancy\Concerns\BelongsToTenant;

class Product extends Model
{
    use BelongsToTenant;
}

// Queries automatically filtered by tenant_id
$products = Product::all(); // WHERE tenant_id = current_tenant_id

// Bypass tenant scope (admin operations)
$allProducts = Product::withoutTenantScope()->get();

3. Use Middleware

// routes/api.php
$router->group(['middleware' => ['tenant']], function ($router) {
    $router->get('/products', [ProductController::class, 'index']);
});

4. Helper Functions

tenant();           // Get current tenant
tenant_id();        // Get current tenant ID
has_tenant();       // Check if tenant context exists
run_as_tenant($tenant, fn() => ...);    // Run in tenant context
run_without_tenant(fn() => ...);        // Run without tenant scope

Configuration

// config/tenancy.php
return [
    'enabled' => true,
    'model' => App\Domain\Entities\Tenant::class,
    'column' => 'tenant_id',

    'resolvers' => [
        'subdomain' => ['enabled' => false, 'base_domain' => 'example.com'],
        'header' => ['enabled' => true, 'name' => 'X-Tenant-ID'],
        'path' => ['enabled' => false],
    ],
];

License

MIT

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 1

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-14