Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Repository Pattern Laravel Package

madulinux/repository-pattern

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require madulinux/repository-pattern
    

    Register the service provider in config/app.php under providers:

    Madulinux\RepositoryPattern\Providers\RepositoryServiceProvider::class,
    
  2. Generate a Repository

    php artisan make:repository User
    

    This creates:

    • app/Repositories/UserRepository.php (implementation)
    • app/Repositories/Interfaces/UserRepositoryInterface.php (contract)
  3. First Use Case: Fetch All Users

    use App\Repositories\UserRepository;
    use App\Models\User;
    
    $repository = new UserRepository(new User());
    $users = $repository->all(); // Returns Collection
    
  4. First Use Case: Create a User

    $user = $repository->create(['name' => 'Alice', 'email' => 'alice@example.com']);
    

Where to Look First

  • Repository Contracts: Check app/Repositories/Interfaces/ for available methods.
  • Base Class: Madulinux\RepositoryPattern\Repository for core functionality.
  • Artisan Commands: php artisan make:repository and php artisan make:repository-interface for scaffolding.

Implementation Patterns

Core Workflows

1. Basic CRUD

// Find
$user = $repository->find(1);

// Create
$user = $repository->create(['name' => 'Bob']);

// Update
$repository->update(1, ['name' => 'Robert']);

// Delete (soft or hard)
$repository->delete(1); // Soft delete if model uses SoftDeletes
$repository->forceDelete(1); // Hard delete

2. Query Scoping

// Chainable queries
$activeUsers = $repository->scopeQuery(function ($query) {
    return $query->where('active', true);
})->get();

// Or use predefined scopes
$repository->scope('active')->get();

3. Pagination

$users = $repository->paginate(10); // Returns LengthAwarePaginator
$users = $repository->simplePaginate(10); // Returns SimplePaginator

4. Bulk Operations

// Bulk create
$users = $repository->createMany([
    ['name' => 'User1'],
    ['name' => 'User2'],
]);

// Bulk update
$repository->updateMany([1, 2], ['status' => 'inactive']);

5. Transactions

$repository->transaction(function ($repo) {
    $repo->create(['name' => 'UserA']);
    $repo->create(['name' => 'UserB']);
    // Rolls back on exception
});

Integration Tips

1. Dependency Injection

Bind repositories in AppServiceProvider:

public function register()
{
    $this->app->bind(
        \App\Repositories\Interfaces\UserRepositoryInterface::class,
        \App\Repositories\UserRepository::class
    );
}

Then inject via constructor:

public function __construct(UserRepositoryInterface $userRepository) {
    $this->userRepository = $userRepository;
}

2. Customizing the Base Repository

Extend the base class for global behavior:

namespace App\Repositories;

use Madulinux\RepositoryPattern\Repository as BaseRepository;

class CustomRepository extends BaseRepository
{
    public function boot()
    {
        $this->applyScopes(['active']);
        $this->enableCache();
    }
}

3. Event Listeners

Listen to repository events in EventServiceProvider:

protected $listen = [
    'Madulinux\RepositoryPattern\Events\Creating' => [
        \App\Listeners\LogCreating::class,
    ],
];

4. Caching Strategies

Configure cache drivers in config/repository-pattern.php:

'cache' => [
    'driver' => 'redis',
    'prefix' => 'repo_',
    'default_ttl' => 60,
],

Enable/disable per repository:

$repository->enableCache(); // Uses config defaults
$repository->enableCache('memcached', 300); // Custom driver/TTL

5. Soft Deletes

Ensure your model uses SoftDeletes trait:

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];
}

Then use:

$repository->withTrashed()->get(); // Include soft-deleted
$repository->onlyTrashed()->get(); // Only soft-deleted

Gotchas and Tips

Pitfalls

  1. Cache Invalidation

    • Caching is automatic for find(), all(), get(), etc., but not for create(), update(), or delete().
    • Fix: Manually clear cache after writes:
      $repository->create([...]);
      $repository->clearCache();
      
    • Tip: Use enableCache(false) for repositories that don’t need caching.
  2. Model Binding

    • The repository must be initialized with a model instance:
      // ❌ Wrong
      $repository = new UserRepository();
      
      // ✅ Correct
      $repository = new UserRepository(new User());
      
  3. Soft Deletes + Cache

    • Cached queries ignore soft-deleted records unless explicitly configured.
    • Fix: Use withTrashed() in your scope:
      $repository->scopeQuery(function ($query) {
          return $query->withTrashed();
      });
      
  4. Transaction Scope

    • Nested transactions won’t work as expected. Use a single transaction block:
      // ❌ Avoid
      $repository->transaction(function ($repo) {
          $repo->transaction(function ($repo) { ... }); // Fails
      });
      
      // ✅ Do
      $repository->transaction(function ($repo) { ... });
      
  5. Bulk Operations and Events

    • Bulk operations (createMany, updateMany) skip Creating, Updating, etc., events by default.
    • Fix: Enable events manually:
      $repository->fireEvents(true)->createMany([...]);
      

Debugging

  1. Query Logging Enable Laravel’s query logging to inspect generated queries:

    \DB::enableQueryLog();
    $repository->all();
    \DB::getQueryLog(); // Inspect queries
    
  2. Event Debugging Dump events in listeners:

    public function handle(Creating $event)
    {
        dd($event->repository, $event->attributes);
    }
    
  3. Cache Debugging Check cached keys:

    $repository->getCacheKey(); // Shows current cache key
    \Cache::getStore()->get($repository->getCacheKey());
    

Extension Points

  1. Custom Scopes Add reusable scopes to the base repository:

    // In a service provider
    $this->app->afterResolving(\Madulinux\RepositoryPattern\Repository::class, function ($repository) {
        $repository->scope('archived', function ($query) {
            return $query->where('archived', true);
        });
    });
    
  2. Custom Events Extend the event system:

    // Fire a custom event
    event(new \App\Events\UserCreated($user));
    
    // Listen in EventServiceProvider
    'App\Events\UserCreated' => [
        \App\Listeners\SendWelcomeEmail::class,
    ];
    
  3. Model Observers Combine with Eloquent observers for additional logic:

    class UserObserver
    {
        public function saved(User $user)
        {
            // Sync with external API, etc.
        }
    }
    

    Register in AppServiceProvider:

    User::observe(UserObserver::class);
    
  4. Repository Decorators Decorate repositories for cross-cutting concerns (e.g., logging, auth):

    class LoggingRepositoryDecorator
    {
        protected $repository;
    
        public function __construct(UserRepositoryInterface $repository)
        {
            $this->repository = $repository;
        }
    
        public function find($id)
        {
            \Log::info("Finding user {$id}");
            return $this->repository->find($id);
        }
    
        // Delegate other methods
        public function __call($method, $args)
        {
            return $this->repository->$method(...$args);
        }
    }
    
  5. **Dynamic Repository

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php