repository-laravel maintained by yuriitatur
Laravel Repository
A Laravel integration package for the yuriitatur/repository repository pattern library. Provides Eloquent and raw-table drivers, fluent repository builders, transaction middleware, and Laravel event bridging.
Installation
composer require yuriitatur/repository-laravel
Register the service provider (auto-discovered in Laravel 5.5+):
// config/app.php
'providers' => [
YuriiTatur\Repository\Laravel\Providers\RepositoryServiceProvider::class,
],
Building a Repository
Eloquent driver
use YuriiTatur\Repository\Laravel\Services\EloquentRepositoryBuilder;
$repository = EloquentRepositoryBuilder::create(UserModel::class)
->forEntity(UserEntity::class) // required unless the model itself is the entity
->build();
The builder auto-selects a hydration strategy based on what the model implements (see Hydration strategies).
Raw-table driver
use YuriiTatur\Repository\Laravel\Services\TableRepositoryBuilder;
$repository = TableRepositoryBuilder::create('users')
->onConnection('pgsql') // optional, defaults to the default connection
->withPrimaryKey('uuid') // optional, auto-detected from schema if omitted
->forEntity(UserEntity::class)
->build();
Custom column matcher or hydrator
Both builders accept overrides:
EloquentRepositoryBuilder::create(UserModel::class)
->withColumnMatcher(MyCustomMatcher::class)
->withHydrator(MyCustomHydrator::class)
->build();
Hydration Strategies
| Strategy | Requirement | How it works |
|---|---|---|
ModelAsEntityHydrator |
Model implements Entity |
Model is used directly as the entity — no conversion |
ModelEntityHydrator |
Model implements HydratorModelInterface |
Model provides toEntity() / fromEntity(Entity $e) |
EloquentEntityHydrator |
->forEntity(MyEntity::class) passed to builder |
JMS Serializer maps model attributes to the entity class |
HydratorModelInterface contract:
interface HydratorModelInterface
{
public function toEntity(): Entity;
public function fromEntity(Entity $entity): void;
}
Transaction Middleware
The service provider registers a transaction middleware alias that wraps the entire request in a database transaction:
// routes/api.php
Route::middleware('transaction')->group(function () {
Route::post('/orders', OrderController::class);
});
It can also be applied per-route or in a controller constructor.
Events
Repository operations dispatch the following events through Laravel's Event facade (bridged from the Symfony EventDispatcher used internally):
| Event | Fired when |
|---|---|
EntitySavedEvent |
An entity is persisted |
EntityDeletedEvent |
An entity is deleted |
EntityHydratedEvent |
A single entity is hydrated from a DB record |
CollectionHydratedEvent |
A collection of entities is hydrated |
RunningQueryEvent |
A query is about to execute |
Listen to them via standard Laravel listeners:
Event::listen(EntitySavedEvent::class, function (EntitySavedEvent $event) {
// ...
});
Testing
composer test
License
MIT — see LICENSE.