vaskiq/eloquent-light-repo 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

vaskiq/eloquent-light-repo

Composer 安装命令:

composer require vaskiq/eloquent-light-repo

包简介

A lightweight repository pattern implementation for Laravel Eloquent models

README 文档

README

A lightweight repository pattern implementation for Laravel Eloquent models.

Compatibility

  • Laravel 11.x
  • Laravel 12.x (Future support)
  • PHP 8.3 or higher

Installation

You can install the package via composer:

composer require vaskiq/eloquent-light-repo

Usage

Create a Repository

Create a repository class for your model by extending the EloquentRepository abstract class:

<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Models\User;
use Vaskiq\EloquentLightRepo\Repositories\EloquentRepository;
use Illuminate\Database\Eloquent\Model;

class UserRepository extends EloquentRepository
{
    public function __construct(User $model)
    {
        parent::__construct($model);
    }

    /**
     * Implement the all() method required by the interface
     */
    public function all(): \Illuminate\Support\Collection
    {
        return $this->query()->get();
    }
}

Use the Repository

<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Repositories\UserRepository;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function __construct(private UserRepository $userRepository)
    {
    }

    public function index()
    {
        $users = $this->userRepository->all();

        return view('users.index', compact('users'));
    }

    public function show($id)
    {
        $user = $this->userRepository->findOrFail($id);

        return view('users.show', compact('user'));
    }

    public function store(Request $request)
    {
        try {
            $user = $this->userRepository->create($request->validated());
            return redirect()->route('users.show', $user->id);
        } catch (\Vaskiq\EloquentLightRepo\Exceptions\CreateException $e) {
            return back()->withErrors(['error' => 'Failed to create user']);
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $user = $this->userRepository->update($id, $request->validated());
            return redirect()->route('users.show', $user->id);
        } catch (\Vaskiq\EloquentLightRepo\Exceptions\UpdateException $e) {
            return back()->withErrors(['error' => 'Failed to update user']);
        }
    }

    public function destroy($id)
    {
        if ($this->userRepository->delete($id)) {
            return redirect()->route('users.index')->with('success', 'User deleted successfully');
        }

        return back()->withErrors(['error' => 'User not found']);
    }
}

Available Methods

  • find(int|string $id, array $columns = ['*']): ?Model - Find a model by ID
  • findOrFail(int|string $id, array $columns = ['*']): Model - Find a model by ID or throw an exception
  • findBy(array|Closure|Expression|null $conditions = null, ?Closure $queryModifier = null, array $columns = ['*']): Collection - Find models by conditions
  • findFirst(array|Closure|Expression|null $conditions = null, ?Closure $queryModifier = null, array $columns = ['*']): ?Model - Find first model by conditions
  • findFirstOrFail(array|Closure|Expression|null $conditions = null, ?Closure $queryModifier = null, array $columns = ['*']): Model - Find first model by conditions or throw exception
  • all(): Collection - Get all models (Note: This method is defined in the interface but must be implemented in your repository class)
  • create(array $data): Model - Create a new model
  • update(int|string $id, array $data, array $options = []): ?Model - Update a model
  • delete(int|string $id): bool - Delete a model by ID
  • deleteModel(Model $model): bool - Delete a model instance
  • deleteBy(array|Closure|Expression|null $conditions = null, ?Closure $queryModifier = null): int - Delete models by conditions
  • chunk(int $count, Closure $callback, ?Closure $queryModifier = null): void - Process models in chunks
  • exists(array|Closure|Expression|null $conditions = null, ?Closure $queryModifier = null, bool $forceRaw = false): bool - Check if models exist
  • count(array|Closure|Expression|null $conditions = null, ?Closure $queryModifier = null, bool $forceRaw = false): int - Count models
  • pluck(string $column, ?string $key = null, ?Closure $queryModifier = null, bool $forceRaw = false): Collection - Get a collection of column values
  • query(): EloquentBuilder - Get a query builder instance
  • raw(): QueryBuilder - Get a raw query builder instance
  • modelClass(): string - Get the model class name
  • new(): Model - Create a new model instance
  • updateOrCreate(array $attributes, array $values): Model - Update or create a model
  • withQueryCollection(?array &$collected = null): self - Collect executed queries for debugging

Debugging

The package provides a method to collect and inspect executed queries:

$queries = [];
$users = $userRepository->withQueryCollection($queries)->all();

// Now $queries contains all executed SQL queries with bindings and execution time
foreach ($queries as $query) {
    echo "SQL: {$query['sql']}\n";
    echo "Bindings: " . json_encode($query['bindings']) . "\n";
    echo "Execution time: {$query['time']}\n";
}

Exceptions

The package provides the following exceptions:

  • CreateException - Thrown when a model creation fails
  • UpdateException - Thrown when a model update fails

Example of handling exceptions:

try {
    $user = $this->userRepository->create($data);
} catch (\Vaskiq\EloquentLightRepo\Exceptions\CreateException $e) {
    // Handle the exception
    $originalException = $e->getPrevious(); // Get the original exception if needed
}

try {
    $user = $this->userRepository->update($id, $data);
} catch (\Vaskiq\EloquentLightRepo\Exceptions\UpdateException $e) {
    // Handle the exception
    $originalException = $e->getPrevious(); // Get the original exception if needed
}

Testing

This package uses Pest PHP for testing. To run the tests:

composer test

For more information about testing, see the tests/README.md file.

License

The Apache License 2.0. Please see License File for more information.

vaskiq/eloquent-light-repo 适用场景与选型建议

vaskiq/eloquent-light-repo 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 391 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 03 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 vaskiq/eloquent-light-repo 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 vaskiq/eloquent-light-repo 我们能提供哪些服务?
定制开发 / 二次开发

基于 vaskiq/eloquent-light-repo 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 391
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 7
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2025-03-11