租赁引导
# 租赁引导
租户引导器是使你的应用程序具有租户意识的类,这样你就不必改变你的一行代码,但工作的范围将仅限于当前租户。
该软件包带有这些开箱即用的引导程序:
# 数据库租约引导程序
数据库租户引导程序在为该租户构建连接后,将 default 数据库连接切换到 tenant
。
注意,只有默认的连接被切换。如果你明确使用另一个连接,无论是使用DB::connection('...')
,还是模型的getConnectionName()
方法,或者像CentralConnection
这样的模型特征,它都会被遵守。
# 缓存租借引导程序
缓存租户引导程序用自定义 CacheManager 替换 Laravel 的 CacheManager 实例,该实例将带有当前租户 ID 的标签添加到每个缓存调用中。 这将使你有选择地清除租户的缓存:
php artisan cache:clear --tag=tenant_123
请注意,你必须使用一个支持标记的缓存存储,例如Redis。
# 文件系统租借引导程序
这个引导程序做了以下事情:
Storage
立面使用的磁盘根的后缀- 后缀
storage_path()
(如果你使用本地磁盘存储租户文件,则很有用)。 - 使得
asset()
调用使用TenantAssetController来检索特定租户的文件- 注意:对于某些资产,例如图片,你可能想使用
global_asset()
(如果该资产为所有租户共享)。而对于JS/CSS资产,你应该使用mix()
或再次使用global_asset()
。 - 因为
asset()
助手使用 TenantAssetController 来检索租户特定的文件。 请注意,这需要对租户进行识别和初始化才能发挥作用。 因此,您应该确保所使用的租户标识中间件适合您的用例(默认为 InitializeTenancyByDomain)。 例如,如果您仅使用子域标识,则应将 TenantAssetController 使用的中间件更新为 InitializeTenancyBySubdomain 中间件。 为此,您可以按照 配置 中概述的步骤更新定义使用的中间件的公共静态属性,例如 在您的 TenancyServiceProvider 中:
- 注意:对于某些资产,例如图片,你可能想使用
use Stancl\Tenancy\Controllers\TenantAssetsController;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomainOrSubdomain;
// other methods in the TenancyServiceProvider
public function boot()
{
// update the middleware used by the asset controller
TenantAssetsController::$tenancyMiddleware = InitializeTenancyByDomainOrSubdomain::class;
}
到目前为止,这个引导器是最复杂的一个。我们很快就会在v3文档中做出更好的解释,但现在,请参考2.x文档中关于文件系统租用的信息。https://tenancyforlaravel.com/docs/v2/filesystem-tenancy/ (opens new window)
如果您不想以这种方式引导文件系统租赁,并且想要(例如)为每个租户配置一个 S3 存储桶,您绝对可以这样做。 查看包的引导程序以了解如何自己编写一个引导程序,并随意以任何您想要的方式实现它。
# 队列租赁引导程序
此引导程序将当前租户的 ID 添加到排队的作业负载中,并在处理作业时基于此 ID 初始化租户。
您可以在 队列 页面上阅读更多相关信息:
# Redis 租赁引导程序
如果您在租户应用程序中使用 Redis
调用(不是缓存调用,直接 Redis 调用),您也将需要限定 Redis 数据的范围。 为此,请使用此引导程序。 它会更改每个租户的 Redis 前缀。
请注意,您需要 phpredis,predis 不起作用。
# 编写自定义引导程序
如果你想为这个扩展没有涵盖的东西引导租户——或者这个扩展涵盖的东西,但你想要不同的行为——你可以通过创建一个引导程序类来做到这一点。
该类必须实现 Stancl\Tenancy\Contracts\TenancyBootstrapper
接口:
namespace App;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
class MyBootstrapper implements TenancyBootstrapper
{
public function bootstrap(Tenant $tenant)
{
// ...
}
public function revert()
{
// ...
}
}
然后,在 tenancy.bootstrappers
配置中注册它:
'bootstrappers' => [
Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper::class,
Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper::class,
Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper::class,
Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper::class,
App\MyBootstrapper::class,
],