jeremy379/laravel-disconnectable
最新稳定版本:0.0.1
Composer 安装命令:
composer require jeremy379/laravel-disconnectable
包简介
Laravel Eloquent trait to disconnect models from the database at runtime
README 文档
README
Disconnect Laravel Eloquent models from their database connection at runtime.
Why this package?
In many applications following Clean Architecture or Hexagonal Architecture, you want to:
- Prevent database connections from leaking into the Domain or Application layers.
- Ensure models returned from the infrastructure layer are read-only and safe to use.
- Avoid accidental lazy-loading or persisting in views, services, or domain objects.
eloquent-disconnectable provides a simple way to “cut” the database connection of a model or collection before returning it from repositories or infrastructure services, while keeping the original model attributes and already loaded relations accessible.
Benefits
- ✅ Prevents lazy-loading of relations.
- ✅ Prevents persistence operations (
save,delete,push) on disconnected models. - ✅ Keeps already loaded relations accessible.
- ✅ Helps enforce Clean Architecture principles by isolating the domain from database concerns.
Installation
Require via Composer:
composer require jeremy379/eloquent-disconnectable
Usage
In a Model
use Illuminate\Database\Eloquent\Model; use YourVendor\EloquentDisconnectable\Disconnectable; class User extends Model { use Disconnectable; }
Disconnect a single model
$transaction = User::with('order')->first(); $disconnected = $transaction->disconnect(); // Access normal attributes echo $disconnected->id; // Access already loaded relations echo $disconnected->order->id; // Attempting DB operations will fail $disconnected->save(); // RuntimeException $disconnected->load('cart'); // RuntimeException $disconnected->otherRelation; // RuntimeException
Why and where to use it
- Infrastructure layer / repository: disconnect models before returning them to the Domain layer.
- Domain layer / services / controllers: ensures models are read-only and cannot accidentally hit the database.
- View / API layer: safe to render attributes and loaded relations without DB risk.
Clean Architecture Enforcement
+-------------------+
| Domain Layer |
| (Entities, DTOs) |
| - No DB access |
+-------------------+
↑
|
+-------------------+
| Infrastructure |
| (Repositories) |
| - DB access only |
+-------------------+
By disconnecting Eloquent models:
- Domain layer never touches the DB.
- Models are pure data objects for business logic.
- Already loaded relations are preserved, so performance stays optimal.
License
MIT © Jérémy Dillenbourg
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-09-04