mawuekom/laravel-repository-layer

Laravel的Repository模式实现

v1.1.2 2021-07-23 19:22 UTC

This package is auto-updated.

Last update: 2024-09-24 02:01:30 UTC


README

本包是Laravel项目的简单Repository模式实现,并可以轻松地从API请求中构建Eloquent查询。

安装

您可以通过composer安装此包

composer require mawuekom/laravel-repository-layer

Laravel

config/app.php中注册服务提供者到providers数组后

'providers' =>
    ...
    Mawuekom\RepositoryLayer\RepositoryLayerServiceProvider::class
    ...
];

发布包配置

php artisan vendor:publish --provider="Mawuekom\RepositoryLayer\RepositoryLayerServiceProvider"

Lumen

转到bootstrap/app.php,并在指定的键中添加以下内容

$app->register(Mawuekom\RepositoryLayer\RepositoryLayerServiceProvider::class);

然后,在根目录中创建config文件夹
完成后,在配置文件夹中创建query-builder.php并添加以下配置

<?php

return [

    /*
     * By default the package will use the `include`, `filter`, `sort`
     * and `fields` query parameters as described in the readme.
     *
     * You can customize these query string parameters here.
     */
    'parameters' => [
        'include' => 'include',

        'filter' => 'filter',

        'sort' => 'sort',

        'fields' => 'fields',

        'append' => 'append',
    ],

    /*
     * Related model counts are included using the relationship name suffixed with this string.
     * For example: GET /users?include=postsCount
     */
    'count_suffix' => 'Count',

    /*
     * By default the package will throw an `InvalidFilterQuery` exception when a filter in the
     * URL is not allowed in the `allowedFilters()` method.
     */
    'disable_invalid_filter_query_exception' => false,

    /*
     * By default the package inspects query string of request using $request->query().
     * You can change this behavior to inspect the request body using $request->input()
     * by setting this value to `body`.
     *
     * Possible values: `query_string`, `body`
     */
    'request_data_source' => 'query_string',
];

同样,在配置文件夹中创建json-api-paginate.php并添加以下配置

<?php

return [

    /*
     * The maximum number of results that will be returned
     * when using the JSON API paginator.
     */
    'max_results' => 30,

    /*
     * The default number of results that will be returned
     * when using the JSON API paginator.
     */
    'default_size' => 30,

    /*
     * The key of the page[x] query string parameter for page number.
     */
    'number_parameter' => 'number',

    /*
     * The key of the page[x] query string parameter for page size.
     */
    'size_parameter' => 'size',

    /*
     * The name of the macro that is added to the Eloquent query builder.
     */
    'method_name' => 'jsonPaginate',

    /*
     * If you only need to display Next and Previous links, you may use
     * simple pagination to perform a more efficient query.
     */
    'use_simple_pagination' => false,

    /*
     * Here you can override the base url to be used in the link items.
     */
    'base_url' => null,

    /*
     * The name of the query parameter used for pagination
     */
    'pagination_parameter' => 'page',
];

完成所有这些后,返回到bootstrap/app.php,并添加您创建的配置文件

$app->configure('query-builder');
$app->configure('json-api-paginate');

此配置允许您根据API请求过滤、排序和包含Eloquent关系。
它还允许根据JSON API规范分页和显示数据。

它使用


请点击以下链接获取更多信息

用法

此包有两个仓库类

  • BaseRepository,它实现了Eloquent模型常用的方法
  • BaseApiRepository,它扩展了BaseRepository并实现了从API请求构建Eloquent查询的附加方法

使用BaseRepository

您的仓库将如下所示

<?php

namespace App\Repositories;

use Mawuekom\RepositoryLayer\BaseRepository;

class UserRepository extends BaseRepository
{
    public function model()
    {
        return Model::class;
    }

    /**
     * Determine the columns on which the search will be done
     */
    public function searchFields(): array
    {
        return [];
    }
}

您的仓库类应扩展自Mawuekom\RepositoryLayer\BaseRepository类,该类实现了接口Mawuekom\RepositoryLayer\Contracts\BaseRepositoryContract,它具有以下方法

<?php

namespace Mawuekom\RepositoryLayer\Contracts;

interface BaseRepositoryContract
{
    /**
     * Get all model's data 
     * 
     * @param array $columns
     * 
     * @return mixed
     */
    public function all($columns = ['*']);

    /**
     * Retrieve the list of data and can add some adjustments to it
     * Like model's relations...
     * 
     * @param string $orderByColumn
     * @param string $orderBy
     * @param array $with
     * @param array $columns
     * 
     * @return mixed
     */
    public function list($orderByColumn, $orderBy = 'desc', $with = [], $columns = ['*']);

    /**
     * Create new data
     * 
     * @param array $data
     * 
     * @return mixed
     */
    public function create(array $data);

    /**
     * Update data by one attribute
     * 
     * @param string $attribute
     * @param string|int $id
     * @param array $data
     * 
     * @return mixed
     */
    public function update(string $attribute, $id, array $data);

    /**
     * Update data by some params
     * 
     * @param array $params
     * @param array $data
     * 
     * @return mixed
     */
    public function updateBy(array $params, array $data);

    /**
     * Delete data by ID
     * 
     * @param int $id
     * 
     * @return mixed
     */
    public function delete($id);

    /**
     * Delete data by some params
     * 
     * @param array $params
     * 
     * @return mixed
     */
    public function deleteBy(array $params);

    /**
     * Search data
     * 
     * @param string|int $searchTerm
     * 
     * @return mixed
     */
    public function search($searchTerm);

    /**
     * Find data by ID
     * 
     * @param int $id
     * @param array $columns
     * 
     * @return mixed
     */
    public function find($id, $columns = ['*']);

    /**
     * Find data by some params
     * 
     * @param array $params
     * @param array $columns
     * 
     * @return mixed
     */
    public function findBy(array $params, $columns = ['*']);

    /**
     * Find all data by some params
     * 
     * @param array $params
     * @param array $columns
     * 
     * @return mixed
     */
    public function findAllBy(array $params, $columns = ['*']);

    /**
     * Get data paginated
     * 
     * @param int $perPages
     * 
     * @return mixed
     */
    public function paginate($perPages = 15);
}

使用BaseApiRepository

您的仓库将如下所示

<?php

namespace App\Repositories;

use Mawuekom\RepositoryLayer\BaseApiRepository;

class UserRepository extends BaseApiRepository
{
    public function model()
    {
        return Model::class;
    }

    /**
     * Determine the columns on which the search will be done
     */
    public function searchFields(): array
    {
        return [];
    }
    
    /**
     * Columns on which filterig will be done
     */
    public function filters(): array
    {
        return ['name', 'first_name', 'gender'];
    }

    /**
     * Determine by which property the results collection will be ordered
     */
    public function sorts(): array
    {
        return [];
    }

    /**
     * Determine the relation that will be load on the resulting model   collection
     */
    public function collectionRelation(): array
    {
        return [];
    }

    /**
     * Determine the relation that will be load on the resulting model resource
     */
    public function resourceRelation(): array
    {
        return [];
    }

    /**
     * Define a couple fields that will be fetch to reduce the overall size of your SQL query
     */
    public function fields(): array
    {
        return [];
    }
}

您的仓库类应扩展自Mawuekom\RepositoryLayer\BaseApiRepository类,该类扩展了Mawuekom\RepositoryLayer\BaseRepository并实现了接口Mawuekom\RepositoryLayer\Contracts\BaseApiRepositoryContract,它具有以下方法

<?php

namespace Mawuekom\RepositoryLayer\Contracts;

interface BaseApiRepositoryContract
{
    /**
     * Get all resources
     * 
     * @return mixed
     */
    public function getAllResources();

    /**
     * Get all resources paginated
     * 
     * @return mixed
     */
    public function paginateAllResources();

    /**
     * Get all resources by
     * 
     * @param array $params
     * 
     * @return mixed
     */
    public function getAllResourcesBy(array $params);

    /**
     * Paginate all resources get by
     * 
     * @param array $params
     * 
     * @return mixed
     */
    public function paginateAllResourcesBy(array $params);

    /**
     * Get resource
     * 
     * @param string $attribute
     * @param string|int $id
     * 
     * @return mixed
     */
    public function getResource(string $attribute, $id);

    /**
     * Get resource by
     * 
     * @param array $params
     * 
     * @return mixed
     */
    public function getResourceBy(array $params);

    /**
     * Search resource
     * 
     * @param string $searchTerm
     * 
     * @return mixed
     */
    public function searchResources($searchTerm);

    /**
     * Paginate searched resources
     * 
     * @param string $searchTerm
     * 
     * @return mixed
     */
    public function paginateSearchResources($searchTerm);
}

希望这个包能帮助您构建出惊人的东西

测试

composer test

变更日志

有关最近更改的更多信息,请参阅CHANGELOG

贡献

有关详细信息,请参阅CONTRIBUTING

安全

如果您发现任何安全相关的问题,请通过电子邮件seddorephraim7@gmail.com联系,而不是使用问题跟踪器。

许可

MIT许可(MIT)。有关更多信息,请参阅许可文件