承接 houlokmah/laravel-tenancy-batch-fix 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

houlokmah/laravel-tenancy-batch-fix

Composer 安装命令:

composer require houlokmah/laravel-tenancy-batch-fix

包简介

Fixes the DatabaseBatchRepository stale connection singleton problem in multi-tenant Laravel apps using stancl/tenancy

README 文档

README

Latest Version on Packagist License

Zero-config fix for the DatabaseBatchRepository stale connection problem in multi-tenant Laravel apps using stancl/tenancy.

If you've ever seen this error in your queue workers:

Call to a member function prepare() on null

...on DatabaseBatchRepository after the first job succeeds but subsequent jobs fail — this package fixes it.

The Problem

There are two layers to this bug:

Layer 1: Connection purging

QueueTenancyBootstrapper calls DB::purge('tenant') after each job completes. This destroys the PDO instance on the cached connection object, setting it to null.

Layer 2: Deferred singleton override

Laravel's BusServiceProvider implements DeferrableProvider. It doesn't load until BatchRepository is first resolved. When it does load, it registers BatchRepository and DatabaseBatchRepository as singletons — overriding any bind() you may have set up in your own service provider.

The combined effect

Job 1 starts
  → Tenancy bootstraps, connects to tenant DB
  → BatchRepository singleton created (holds live connection) ✅
  → Job completes
  → QueueTenancyBootstrapper calls DB::purge() → PDO set to null

Job 2 starts
  → Tenancy bootstraps new tenant DB
  → BatchRepository resolves → returns SAME singleton (stale connection, null PDO)
  → prepare() on null 💥

The same issue occurs in the scheduler when using runForMultiple() to iterate through tenants.

The Solution

This package applies a three-pronged fix:

  1. register() — Binds BatchRepository and DatabaseBatchRepository using bind() instead of singleton(), creating a fresh instance per resolution.

  2. TenancyBootstrapped listener — Re-applies the bind() after each tenant switch, clearing any cached singleton that the deferred BusServiceProvider may have created.

  3. Queue::before() listener — Safety net that re-binds before every queued job, covering central-connection jobs where TenancyBootstrapped doesn't fire.

Why this works

  • Container::bind() calls dropStaleInstances(), which removes any cached singleton
  • The closure inside bind() resolves DB::connection() at resolution time (not registration time), so it always gets the current live tenant connection
  • Queue::before() fires after QueueTenancyBootstrapper initializes the tenant (because the bootstrapper registers its listener during the register phase, while our Queue::before registers in boot)

Installation

composer require houlokmah/laravel-tenancy-batch-fix

Then restart your queue workers:

php artisan queue:restart

That's it. The package uses Laravel's auto-discovery — no manual service provider registration needed.

Configuration (Optional)

For most apps, zero configuration is needed. If you need to customize the batch table name or database connection:

php artisan vendor:publish --tag=tenancy-batch-fix-config

This publishes config/tenancy-batch-fix.php:

return [
    // Override batch table name (default: falls through to queue.batching.table)
    'table' => null,

    // Override database connection (default: falls through to queue.batching.database)
    'connection' => null,
];

Execution Flow

Before (broken)

Worker boots → AppServiceProvider bind()
            → Job 1 resolves BatchRepository
            → BusServiceProvider loads (deferred) → overrides with singleton()
            → Job 1 succeeds
            → DB::purge() → PDO = null
            → Job 2 resolves BatchRepository → gets stale singleton → 💥

After (fixed)

Worker boots → TenancyBatchFixServiceProvider bind()
            → Job 1 resolves BatchRepository → fresh instance ✅
            → BusServiceProvider loads (deferred) → overrides with singleton()
            → Job 1 succeeds
            → DB::purge() → PDO = null
            → Queue::before fires → re-binds (clears stale singleton)
            → TenancyBootstrapped fires → re-binds again (belt + suspenders)
            → Job 2 resolves BatchRepository → fresh instance ✅

Requirements

How It Works (Deep Dive)

Why bind() clears the singleton

Laravel's Container::bind() method calls dropStaleInstances($abstract), which removes the key from both $this->instances (where singletons are cached) and $this->aliases. This is the mechanism that clears the stale DatabaseBatchRepository singleton.

Why BusServiceProvider overrides our binding

BusServiceProvider implements DeferrableProvider and declares BatchRepository::class in its provides() method. Laravel's deferred provider mechanism means the provider only loads when one of its provided abstracts is first resolved. At that point, its register() method runs and calls singleton(), which replaces any bind() we set up earlier.

Why Queue::before fires after tenancy initialization

QueueTenancyBootstrapper::__constructStatic() registers its JobProcessing listener during the service provider register phase (via Event::listen). Our Queue::before() registers during boot(), which runs later. Since Laravel dispatches listeners in registration order, the tenancy bootstrapper's listener fires first (initializing the tenant connection), and our listener fires second (re-binding with the now-live connection).

Why we bind both abstracts

BusServiceProvider::registerBatchServices() registers singletons for both BatchRepository::class and DatabaseBatchRepository::class. If we only override BatchRepository, the deferred provider's cached singleton for DatabaseBatchRepository could still surface. Overriding both ensures no stale instances remain.

Testing

composer test

Or directly:

vendor/bin/phpunit

License

The MIT License (MIT). See LICENSE for details.

houlokmah/laravel-tenancy-batch-fix 适用场景与选型建议

houlokmah/laravel-tenancy-batch-fix 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「queue」 「laravel」 「batch」 「multi-tenant」 「tenancy」 「stancl」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 houlokmah/laravel-tenancy-batch-fix 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 houlokmah/laravel-tenancy-batch-fix 我们能提供哪些服务?
定制开发 / 二次开发

基于 houlokmah/laravel-tenancy-batch-fix 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-17