ananiaslitz / matrix
适用于 Hyperf API 的多租户库。
dev-main
2024-02-05 20:02 UTC
Requires
- php: ^8.0
- hyperf/command: ^3.0
- hyperf/database: ^3.0
- hyperf/db-connection: *
- hyperf/di: ^3.0
Requires (Dev)
- hyperf/testing: ^3.0
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-09-05 21:11:31 UTC
README
Matrix 是一个全面的多租户库,旨在无缝地将多租户集成到您的 Hyperf 应用程序中。它提供了一个易于使用且灵活的系统来管理多个租户,确保数据隔离、动态数据库连接管理和基于请求参数的租户识别。
🌟 特点
- 动态租户数据库连接:根据识别的租户自动切换数据库连接,确保每个租户的数据保持隔离和安全。
- 可定制租户识别:灵活定义如何从传入请求中识别租户,无论是通过子域名、路径、头信息或其他自定义策略。
- 可扩展架构:利用库的依赖注入和配置系统,可以轻松扩展或覆盖默认行为。
- 发布迁移的命令:包括一个命令将必要的迁移发布到应用程序中,使设置快速直接。
🚀 安装
要安装 Matrix,请在 Hyperf 项目的根目录下运行以下命令
composer require ananiaslitz/matrix
安装后,您应该发布 Matrix 提供的默认迁移
php bin/hyperf.php matrix:publish
此命令将必要的迁移文件复制到您的项目 migrations
目录。
配置
- 发布配置(可选):如果您想自定义租户识别逻辑或使用自定义的 TenantFinder,发布 Matrix 配置文件
php bin/hyperf.php vendor:publish ananiaslitz/matrix
这会将默认配置文件复制到 config/autoload/matrix.php
。
- 定义 租户查找器:在
config/autoload/matrix.php
中,如果需要,指定您的自定义 租户查找器 实现
return [ 'tenant_finder' => App\Tenant\CustomTenantFinder::class, ];
- 中间件注册:在应用程序的中间件堆栈中注册
TenantMiddleware
,通常在config/autoload/middlewares.php
return [ 'http' => [ \Ananiaslitz\Matrix\Http\Middleware\TenantMiddleware::class, ], ];
使用
要在您的应用程序中使用 Matrix,只需像平常一样继续处理业务逻辑。库会根据您的配置自动处理租户识别和数据库连接切换。
确保您的租户特定模型使用动态租户连接,这是 Matrix 根据识别的租户配置的
namespace App\Model; use Hyperf\DbConnection\Model\Model; use Ananiaslitz\Matrix\Model\Traits\UsesTenantConnection; class YourTenantModel extends Model { use UsesTenantConnection; }
自定义租户识别
要自定义租户的识别方式,实现自己的 TenantFinderInterface
并在 config/autoload/matrix.php
配置文件中指定它。您的自定义查找器应根据请求返回租户标识符,Matrix 将使用它来配置数据库连接。
贡献
欢迎贡献!请随时提交拉取请求或创建有关错误、问题和功能请求的问题。