monobridge / eloquent
Zero-duplication cross-service Eloquent model bridge for Laravel microservices and Docker monorepos.
Requires
- php: ^8.1 || ^8.2 || ^8.3 || ^8.4
- illuminate/console: ^10.0 || ^11.0 || ^12.0
- illuminate/database: ^10.0 || ^11.0 || ^12.0
- illuminate/support: ^10.0 || ^11.0 || ^12.0
Requires (Dev)
- phpunit/phpunit: ^10.5 || ^11.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Zero-duplication cross-service Eloquent model bridge for Laravel microservices & Docker monorepos.
Stop copy-pasting Eloquent models across your api, app, admin, and worker Laravel microservices. Keep every model in the service that owns the schema, and let MonoBridge Eloquent seamlessly autoload, query, and manage all Eloquent models across your services with zero code duplication.
Table of Contents
- How It Works
- Features
- Requirements
- Installation
- Quickstart (Step-by-Step)
- Configuration Reference
- Usage Patterns
- Safely Cleaning Up Existing Duplicate Models
- Artisan Commands Reference
- IDE Autocomplete (VS Code & PhpStorm)
- Production Deployment & Caching
- Troubleshooting & FAQ
- Testing
- License
How It Works
┌──────────────────────────────────────────┐
│ Owning Service (e.g. apps/api) │
│ apps/api/app/Models/ │
│ ├── Pub/Currency.php │
│ ├── Pub/Order.php │
│ └── ... (all Eloquent models) │
└────────────────────┬─────────────────────┘
│
Mounted read-only (:ro) in Docker / local path
┌─────────────────┴─────────────────┐
▼ ▼
┌───────────────────────────┐ ┌───────────────────────────┐
│ Frontend (apps/app) │ │ Admin (apps/admin-app) │
│ monobridge/eloquent │ │ monobridge/eloquent │
│ │ │ │
│ use App\Models\Pub\ │ │ use App\Models\Pub\ │
│ Currency; │ │ Currency; │
│ Currency::all(); // OK! │ │ Currency::all(); // OK! │
└───────────────────────────┘ └───────────────────────────┘
- Your owning microservice (e.g.
api) keeps all its Eloquent models in its normalapp/Models/directory—no restructuring required. - Each consuming microservice (e.g.
app,admin-app) mounts the owning service'sapp/Modelsdirectory read-only (:ro) in Docker (or points directly to the relative directory on disk in non-Docker setups). - MonoBridge Eloquent registers a fast PSR-4 cross-service autoloader at boot. Whenever a consuming service references a model that does not exist locally (or overrides it, if configured), MonoBridge resolves it directly from the owning service.
- Any schema, cast, scope, or relationship change you make in
api/app/Models/is immediately reflected across every consuming microservice.
Features
- Zero Model Duplication — Maintain a single source of truth for every table/model.
- Works With ALL Eloquent Models Automatically — Zero per-model boilerplate; new models added to the source service are instantly available everywhere.
- Relationships Just Work — When a bridged model references related models (e.g.
Currency→CompanyCurrencyRate), MonoBridge automatically autoloads those related models too. fallback&overrideStrategies — Keep service-local models (likeUser) isolated by default (fallback), or let bridged models take priority (override).- Wildcard Filtering (
only/except) — Expose all models or restrict to specific folders/classes (e.g.'only' => ['Pub\\*'],'except' => ['User']). - Optional Alias Namespaces — Import external models under a dedicated namespace (e.g.
ApiModels\Pub\Currency). - Per-Bridge Database Connection Binding — Automatically attach a bridge's DB connection when using
MonoBridge::from('billing')->query(...). - O(1) Production Classmap Caching —
php artisan monobridge:cacheeliminates runtime directory lookups in production. - IDE Autocomplete Support —
php artisan monobridge:ide-helpergenerates stubs for VS Code (Intelephense) and PhpStorm. - Built-in Diagnostics —
php artisan monobridge:doctorvalidates Docker volume mounts and detects redundant local model copies.
Requirements
- PHP:
^8.1 | ^8.2 | ^8.3 | ^8.4 - Laravel:
^10.0 | ^11.0 | ^12.0
Installation
Install monobridge/eloquent in every consuming Laravel microservice (e.g. app, admin-app).
Option A: From Packagist or Private Registry (Satis / Private Packagist / Git VCS)
composer require monobridge/eloquent
Or via a private Git repository in your microservice's composer.json:
{
"repositories": [
{
"type": "vcs",
"url": "git@github.com:your-org/monobridge-eloquent.git"
}
],
"require": {
"monobridge/eloquent": "^1.0"
}
}
Option B: Local Monorepo Path Repository
If you keep the package inside a packages/ folder in your monorepo:
- Mount
./packages:/var/packagesin your Docker Compose services (so relative paths resolve identically inside Docker and on host). - Add the path repository to each service's
composer.json:
{
"repositories": [
{
"name": "monobridge-eloquent",
"type": "path",
"url": "../../packages/monobridge-eloquent",
"options": {
"symlink": true
}
}
],
"require": {
"monobridge/eloquent": "@dev"
}
}
- Install the package inside each container:
docker exec <container-name> composer update monobridge/eloquent
Quickstart (Step-by-Step)
Step 1: Mount Source Models in Docker (or Set Local Path)
Docker Compose Setup
Mount the owning service's app/Models folder read-only (:ro) into every consuming container:
services: api: volumes: - ./apps/api:/var/www/api app: volumes: - ./apps/app:/var/www/app - ./apps/api/app/Models:/var/monobridge/api/Models:ro admin-app: volumes: - ./apps/admin-app:/var/www/admin - ./apps/api/app/Models:/var/monobridge/api/Models:ro
Recreate the containers so the new mounts take effect:
docker compose up -d app admin-app
Non-Docker (Local Monorepo) Setup
No volume mount needed—just point MONOBRIDGE_API_PATH in .env (or config/monobridge.php) to the relative path on disk:
MONOBRIDGE_API_PATH=../api/app/Models
Step 2: Publish & Configure config/monobridge.php
Run the installer inside each consuming service:
php artisan monobridge:install
Open config/monobridge.php and register your source service(s) under bridges:
<?php return [ 'enabled' => env('MONOBRIDGE_ENABLED', true), 'strategy' => env('MONOBRIDGE_STRATEGY', 'fallback'), 'cache_path' => base_path('bootstrap/cache/monobridge.php'), 'bridges' => [ 'api' => [ 'enabled' => true, 'path' => env('MONOBRIDGE_API_PATH', '/var/monobridge/api/Models'), 'namespace' => 'App\\Models\\', 'alias_namespace' => env('MONOBRIDGE_API_ALIAS_NAMESPACE', null), 'connection' => env('MONOBRIDGE_API_CONNECTION', null), 'only' => [], 'except' => ['User'], // Keep each microservice's local Auth User separate ], ], 'ide_helper' => [ 'path' => base_path('_ide_helper_monobridge.php'), ], ];
Step 3: Verify Setup with monobridge:doctor
Run the diagnostic command inside your consuming service container:
php artisan monobridge:doctor
Example output:
MonoBridge Eloquent Diagnostics
--------------------------------------------------
Status: Enabled
Strategy: fallback
Autoloader: Registered
Classmap: Dynamic (Live Scan)
[OK] Bridge [api] -> /var/monobridge/api/Models (154 models, 0 local duplicates)
All bridges healthy! 154 model(s) available with zero local duplicates.
Step 4: Use Any Model from Your Other Services
Import and query any Eloquent model from the bridged service just like a local model:
use App\Models\Pub\Currency; use App\Models\Pub\Policy; $currencies = Currency::with('company_rates')->where('status', 1)->get(); $latestPolicies = Policy::latest()->limit(20)->get();
No files copied. No manual model registration.
Configuration Reference
| Key | Type | Default | Description |
|---|---|---|---|
enabled |
bool |
true |
Globally enable or disable MonoBridge autoloading. |
strategy |
string |
'fallback' |
'fallback': local models win, missing models load from bridges. 'override': bridged models win over local duplicates. |
cache_path |
string |
bootstrap/cache/monobridge.php |
Output file path for php artisan monobridge:cache. |
bridges.<name>.enabled |
bool |
true |
Enable or disable an individual bridge. |
bridges.<name>.path |
string |
'' |
Absolute (or relative) path to the source service's Models directory. |
bridges.<name>.namespace |
string |
'App\\Models\\' |
PSR-4 namespace declared inside the source model files. |
bridges.<name>.alias_namespace |
?string |
null |
Optional secondary namespace (e.g. 'ApiModels\\') to import bridged models explicitly. |
bridges.<name>.connection |
?string |
null |
Optional Laravel DB connection name applied automatically when using MonoBridge::make() or MonoBridge::query(). |
bridges.<name>.only |
string[] |
[] |
Allowlist of relative class patterns (supports * wildcard, e.g. ['Pub\\*', 'Country']). Empty allows all. |
bridges.<name>.except |
string[] |
[] |
Denylist of relative class patterns (e.g. ['User', 'Internal\\*']). |
ide_helper.path |
string |
_ide_helper_monobridge.php |
Output path for php artisan monobridge:ide-helper. |
Optional .env Variables
MONOBRIDGE_ENABLED=true MONOBRIDGE_STRATEGY=fallback MONOBRIDGE_API_PATH=/var/monobridge/api/Models MONOBRIDGE_API_ALIAS_NAMESPACE= MONOBRIDGE_API_CONNECTION=
Usage Patterns
1. Native Imports (Zero Refactoring)
With 'namespace' => 'App\\Models\\', you keep standard Laravel imports everywhere:
use App\Models\Pub\Currency; $usd = Currency::where('code', 'USD')->first();
If Currency.php does not exist in app/Models/Pub/, MonoBridge loads it directly from your bridged service.
2. Alias Namespaces
If you want to make cross-service imports visually explicit in your codebase, configure 'alias_namespace' => 'ApiModels\\':
use ApiModels\Pub\Currency; use ApiModels\Pub\Order; $currencies = Currency::all(); $orders = Order::where('paid', true)->get();
Note: Because PHP cannot declare two different classes with the exact same FQCN in one process, an alias class cannot be loaded if a different local file already loaded the same underlying FQCN (e.g.
App\Models\User). Exclude local-only classes with'except' => ['User'], or MonoBridge will throw a descriptiveNamespaceCollisionException.
3. Fluent MonoBridge Facade & Connection Binding
Use the MonoBridge facade for dynamic model resolution, multi-database connection binding, or runtime introspection:
use MonoBridge\Eloquent\Facades\MonoBridge; // Query by relative path or short class name (auto-binds bridge DB connection if configured) $activeCurrencies = MonoBridge::from('api') ->query('Pub\\Currency') ->where('status', 1) ->get(); // Short class name resolution (when unambiguous) $currency = MonoBridge::from('api')->make('Currency', ['code' => 'USD']); // Resolve to full FQCN string $fqcn = MonoBridge::from('api')->resolve('Pub\\Currency'); // "App\Models\Pub\Currency" // Inspect bridged models at runtime $allModels = MonoBridge::discoverModels(); $apiModels = MonoBridge::from('api')->models(); $isBridged = MonoBridge::has(\App\Models\Pub\Currency::class); $bridge = MonoBridge::bridgeFor(\App\Models\Pub\Currency::class);
4. Bridging Multiple Microservices
You can bridge models from as many services as you need:
'bridges' => [ 'api' => [ 'path' => env('MONOBRIDGE_API_PATH', '/var/monobridge/api/Models'), 'namespace' => 'App\\Models\\', 'connection' => 'pgsql_core', 'except' => ['User'], ], 'billing' => [ 'path' => env('MONOBRIDGE_BILLING_PATH', '/var/monobridge/billing/Models'), 'namespace' => 'App\\Models\\', 'alias_namespace' => 'BillingModels\\', 'connection' => 'pgsql_billing', 'only' => ['Invoice', 'Subscription', 'Payment\\*'], ], ],
Safely Cleaning Up Existing Duplicate Models
If you are adopting MonoBridge in an existing project that already has copied model files across services:
- Keep
'strategy' => 'fallback'(the default) so nothing breaks while migrating. - List all local files that duplicate a bridged model:
php artisan monobridge:models --shadowed
- Compare a duplicated file against the source service's version. Once confirmed identical (or after moving any needed methods to the source service), delete the local duplicate file.
- Important: If your
composer.jsonhas"optimize-autoloader": true, regenerate Composer's classmap after deleting local model files:composer dump-autoload
- Re-run
php artisan monobridge:doctorto verify the duplicate count drops to zero.
Artisan Commands Reference
| Command | Options | Description |
|---|---|---|
php artisan monobridge:install |
--force |
Publish config/monobridge.php into your Laravel app. |
php artisan monobridge:doctor |
— | Check bridge status, Docker mounts, cache state, and duplicate local models. |
php artisan monobridge:models |
--bridge=<name>, --shadowed |
Display a table of all discovered bridged models, aliases, connections, and status. |
php artisan monobridge:cache |
— | Build an O(1) static classmap at bootstrap/cache/monobridge.php. |
php artisan monobridge:clear |
— | Delete the cached classmap file and return to live scanning. |
php artisan monobridge:ide-helper |
--path=<file> |
Generate _ide_helper_monobridge.php for IDE autocompletion. |
IDE Autocomplete (VS Code & PhpStorm)
Because bridged models live outside a consumer service's app/Models folder, static analyzers or IDEs opened on a single service folder may show "Undefined type" warnings.
Generate the IDE helper stub file:
php artisan monobridge:ide-helper
This creates _ide_helper_monobridge.php in your app root (add it to your service's .gitignore):
_ide_helper_monobridge.php
Re-run php artisan monobridge:ide-helper whenever you add new models to your source service.
Production Deployment & Caching
For maximum performance in production:
- Mount source model directories as read-only (
:ro) in production Docker Compose / Kubernetes volumes. - Add
monobridge:cacheto your deployment script right alongside Laravel's standard caches:php artisan config:cache php artisan route:cache php artisan view:cache php artisan monobridge:cache
- When
bootstrap/cache/monobridge.phpexists, MonoBridge resolves bridged classes via a single O(1) PHP array lookup with zero directory scanning. - Remember to add
/bootstrap/cache/monobridge.phpto.gitignore(usually already covered by/bootstrap/cache/*.php).
Troubleshooting & FAQ
Class "App\Models\..." not found
- Run
php artisan monobridge:doctorinside the container to confirm the mount path exists and is readable. - Ensure the file's namespace inside the source service matches
bridges.<name>.namespace. - If you previously ran
php artisan monobridge:cache, re-run it (orphp artisan monobridge:clear) so newly added models are picked up.
Still loading an old copy of a model after deleting the local file?
- If
composer.jsonhas"optimize-autoloader": true, Composer's static classmap still references the deleted local path. Run:composer dump-autoload
NamespaceCollisionException when using alias_namespace
- The underlying class (e.g.
App\Models\User) was already loaded from a local file in the current service before the alias was requested. Either remove the local duplicate model or add it to'except' => ['User']inconfig/monobridge.php.
Do model dependencies (Traits, Helpers, Enums) need to exist in consumer services?
- If a bridged model references another model in the same bridged
Models/directory, MonoBridge autoloads it automatically. - If a bridged model references a custom Helper, Trait, or Enum outside
app/Models/(for example,App\Enums\OrderStatus), either ensure that class exists in the consumer service or add a second bridge entry pointing toapp/Enumswith'namespace' => 'App\\Enums\\'.
Testing
Run the package test suite with PHPUnit:
composer test
Or directly via PHPUnit:
vendor/bin/phpunit
License
MonoBridge Eloquent is open-sourced software licensed under the MIT license.