Installation Add the package via Composer:
composer require c33s/entity-loader-bundle
Register the bundle in config/app.php under providers:
C33S\EntityLoaderBundle\EntityLoaderBundle::class,
Basic Configuration
Define your entity loader in config/entity_loader.php:
return [
'entities' => [
'App\\Models\\Product' => [
'path' => storage_path('app/entities/products'),
'file_extension' => '.php',
],
],
];
First Use Case: Loading an Entity
Use the EntityLoader service to load or create an entity:
use C33S\EntityLoaderBundle\EntityLoader;
$loader = app(EntityLoader::class);
$product = $loader->loadOrCreate('App\Models\Product', 'product_123', [
'name' => 'Laptop',
'price' => 999.99,
]);
Create/Update
Use loadOrCreate to persist data to a PHP file:
$entity = $loader->loadOrCreate(
'App\Models\Product',
'product_123',
['name' => 'Updated Name']
);
Read Fetch an entity by ID:
$product = $loader->load('App\Models\Product', 'product_123');
Delete Remove an entity file:
$loader->delete('App\Models\Product', 'product_123');
Extend Eloquent models to auto-load from files:
use C33S\EntityLoaderBundle\EntityLoader;
class Product extends Model
{
public static function boot()
{
parent::boot();
static::addGlobalScope('EntityLoader', function (Builder $builder) {
$loader = app(EntityLoader::class);
$builder->getQuery()->from(function ($query) use ($loader) {
// Custom logic to merge DB and file-based data
});
});
}
}
Load multiple entities at once:
$products = $loader->loadMultiple('App\Models\Product', ['product_123', 'product_456']);
File Permissions
Ensure the storage directory (storage_path('app/entities')) is writable:
chmod -R 775 storage/app/entities
Circular Dependencies
Avoid circular references in entity data (e.g., Product referencing Category which references Product).
Overwriting Data
loadOrCreate merges data by default. Use force: true to overwrite:
$loader->loadOrCreate('App\Models\Product', 'product_123', [], true);
path in config matches the actual directory.product_123 ≠ Product_123).Custom File Naming Override the default filename generator:
$loader->setFilenameGenerator(function ($id) {
return 'custom_' . strtolower($id) . '.php';
});
Event Listeners
Hook into EntityLoaded, EntityCreated, or EntityDeleted events via the bundle’s event system:
Event::listen('entity_loader.entity.loaded', function ($entity) {
// Post-load logic
});
Hybrid Storage
Combine with a database by implementing a Repository interface:
class HybridRepository implements RepositoryInterface
{
public function find($id)
{
// Check DB first, fall back to file
}
}
How can I help you explore Laravel packages today?