ark4ne/laravel-repository

Laravel 仓库实现

v0.1.0 2021-06-06 20:12 UTC

This package is auto-updated.

Last update: 2024-09-07 03:07:34 UTC


README

Laravel 仓库实现

Build Status Coverage Status

用法

use Illuminate\Database\Eloquent\Model;

class Pet extends Model {
    // ...
}
use Ark4ne\Repositories\Contracts\RepositoryContract;

interface PetRepositoryContract extends RepositoryContract {
    //
}
use Ark4ne\Repositories\Eloquent\Repository;

class PetRepository extends Repository implements PetRepositoryContract {
    protected function getModel() : Pet {
        return new Pet;
    }
}
// RepositoryServiceProvider.php

public function register() {
    $this->app->bind(PetRepositoryContract::class, PetRepository::class);
}
// PetController.php

class PetController extends Controller {
    private $repository;
    
    public function __construct(PetRepositoryContract $repository) {
        $this->repository = $repository;
    }
    
    public function store(PetStoreRequest $request) {
        $data = $request->validated();
        
        $pet = $this->repository->store($data);
        
        return new PetResource($pet);
    }
}

方法

count

统计符合$criteria条件的模型。

count(array<string, null|int|string|Closure> $criteria): int

all

返回所有符合$criteria条件的模型。

all(): \Illuminate\Support\Collection

paginate

返回符合$criteria条件的模型分页列表。

paginate(array<string, null|int|string|Closure> $criteria, int|null $per_page): \Illuminate\Contracts\Pagination\LengthAwarePaginator

find

通过id返回一个模型。

find(int|string $id): \Illuminate\Database\Eloquent\Model

findBy

返回一个字段的值匹配给定值的模型。

findBy(string $field, mixed $value): \Illuminate\Database\Eloquent\Model

findByMany

返回符合$criteria条件的模型。

findByMany(array<string, null|int|string|Closure> $criteria): \Illuminate\Database\Eloquent\Model

getWhere

返回字段值匹配给定值的模型集合。

getWhere(string $field, mixed $value): \Illuminate\Support\Collection

getWhereMany

返回符合$criteria条件的模型集合。

getWhereMany(array<string, null|int|string|Closure> $criteria): \Illuminate\Support\Collection

store

创建并返回一个新的模型。

store(array<string, mixed> $data): \Illuminate\Database\Eloquent\Model

update

更新现有的模型。

update(int|string $id, array<string, mixed> $data): \Illuminate\Database\Eloquent\Model

delete

删除现有的模型。

delete(int|string $id): bool

withCriteria

添加条件。

withCriteria(array<string, null|int|string|Closure> $criteria): self

withRelationships

添加应该被懒加载的关系。

withRelationships(array<string> $relationships): self