• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

andersao/l5-repository: Laravel 5 - Repositories to abstract the database layer

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

andersao/l5-repository

开源软件地址(OpenSource Url):

https://github.com/andersao/l5-repository

开源编程语言(OpenSource Language):

PHP 100.0%

开源软件介绍(OpenSource Introduction):

Laravel 5 Repositories

Laravel 5 Repositories is used to abstract the data layer, making our application more flexible to maintain.

Latest Stable Version Total Downloads Latest Unstable Version License Analytics Code Climate

See versions: 1.0.* / 2.0.*

Migrate to: 2.0 / 2.1

You want to know a little more about the Repository pattern? Read this great article.

Table of Contents

Installation

Composer

Execute the following command to get the latest version of the package:

composer require prettus/l5-repository

Laravel

>= laravel5.5

ServiceProvider will be attached automatically

Other

In your config/app.php add Prettus\Repository\Providers\RepositoryServiceProvider::class to the end of the providers array:

'providers' => [
    ...
    Prettus\Repository\Providers\RepositoryServiceProvider::class,
],

If Lumen

$app->register(Prettus\Repository\Providers\LumenRepositoryServiceProvider::class);

Publish Configuration

php artisan vendor:publish --provider "Prettus\Repository\Providers\RepositoryServiceProvider"

Methods

Prettus\Repository\Contracts\RepositoryInterface

  • all($columns = array('*'))
  • first($columns = array('*'))
  • paginate($limit = null, $columns = ['*'])
  • find($id, $columns = ['*'])
  • findByField($field, $value, $columns = ['*'])
  • findWhere(array $where, $columns = ['*'])
  • findWhereIn($field, array $where, $columns = [*])
  • findWhereNotIn($field, array $where, $columns = [*])
  • findWhereBetween($field, array $where, $columns = [*])
  • create(array $attributes)
  • update(array $attributes, $id)
  • updateOrCreate(array $attributes, array $values = [])
  • delete($id)
  • deleteWhere(array $where)
  • orderBy($column, $direction = 'asc');
  • with(array $relations);
  • has(string $relation);
  • whereHas(string $relation, closure $closure);
  • hidden(array $fields);
  • visible(array $fields);
  • scopeQuery(Closure $scope);
  • getFieldsSearchable();
  • setPresenter($presenter);
  • skipPresenter($status = true);

Prettus\Repository\Contracts\RepositoryCriteriaInterface

  • pushCriteria($criteria)
  • popCriteria($criteria)
  • getCriteria()
  • getByCriteria(CriteriaInterface $criteria)
  • skipCriteria($status = true)
  • getFieldsSearchable()

Prettus\Repository\Contracts\CacheableInterface

  • setCacheRepository(CacheRepository $repository)
  • getCacheRepository()
  • getCacheKey($method, $args = null)
  • getCacheTime()
  • skipCache($status = true)

Prettus\Repository\Contracts\PresenterInterface

  • present($data);

Prettus\Repository\Contracts\Presentable

  • setPresenter(PresenterInterface $presenter);
  • presenter();

Prettus\Repository\Contracts\CriteriaInterface

  • apply($model, RepositoryInterface $repository);

Prettus\Repository\Contracts\Transformable

  • transform();

Usage

Create a Model

Create your model normally, but it is important to define the attributes that can be filled from the input form data.

namespace App;

class Post extends Eloquent { // or Ardent, Or any other Model Class

    protected $fillable = [
        'title',
        'author',
        ...
     ];

     ...
}

Create a Repository

namespace App;

use Prettus\Repository\Eloquent\BaseRepository;

class PostRepository extends BaseRepository {

    /**
     * Specify Model class name
     *
     * @return string
     */
    function model()
    {
        return "App\\Post";
    }
}

Generators

Create your repositories easily through the generator.

Config

You must first configure the storage location of the repository files. By default is the "app" folder and the namespace "App". Please note that, values in the paths array are acutally used as both namespace and file paths. Relax though, both foreward and backward slashes are taken care of during generation.

    ...
    'generator'=>[
        'basePath'=>app()->path(),
        'rootNamespace'=>'App\\',
        'paths'=>[
            'models'       => 'Entities',
            'repositories' => 'Repositories',
            'interfaces'   => 'Repositories',
            'transformers' => 'Transformers',
            'presenters'   => 'Presenters',
            'validators'   => 'Validators',
            'controllers'  => 'Http/Controllers',
            'provider'     => 'RepositoryServiceProvider',
            'criteria'     => 'Criteria',
        ]
    ]

You may want to save the root of your project folder out of the app and add another namespace, for example

    ...
     'generator'=>[
        'basePath'      => base_path('src/Lorem'),
        'rootNamespace' => 'Lorem\\'
    ]

Additionally, you may wish to customize where your generated classes end up being saved. That can be accomplished by editing the paths node to your liking. For example:

    'generator'=>[
        'basePath'=>app()->path(),
        'rootNamespace'=>'App\\',
        'paths'=>[
            'models'=>'Models',
            'repositories'=>'Repositories\\Eloquent',
            'interfaces'=>'Contracts\\Repositories',
            'transformers'=>'Transformers',
            'presenters'=>'Presenters'
            'validators'   => 'Validators',
            'controllers'  => 'Http/Controllers',
            'provider'     => 'RepositoryServiceProvider',
            'criteria'     => 'Criteria',
        ]
    ]

Commands

To generate everything you need for your Model, run this command:

php artisan make:entity Post

This will create the Controller, the Validator, the Model, the Repository, the Presenter and the Transformer classes. It will also create a new service provider that will be used to bind the Eloquent Repository with its corresponding Repository Interface. To load it, just add this to your AppServiceProvider@register method:

    $this->app->register(RepositoryServiceProvider::class);

You can also pass the options from the repository command, since this command is just a wrapper.

To generate a repository for your Post model, use the following command

php artisan make:repository Post

To generate a repository for your Post model with Blog namespace, use the following command

php artisan make:repository "Blog\Post"

Added fields that are fillable

php artisan make:repository "Blog\Post" --fillable="title,content"

To add validations rules directly with your command you need to pass the --rules option and create migrations as well:

php artisan make:entity Cat --fillable="title:string,content:text" --rules="title=>required|min:2, content=>sometimes|min:10"

The command will also create your basic RESTfull controller so just add this line into your routes.php file and you will have a basic CRUD:

Route::resource('cats', CatsController::class);

When running the command, you will be creating the "Entities" folder and "Repositories" inside the folder that you set as the default.

Now that is done, you still need to bind its interface for your real repository, for example in your own Repositories Service Provider.

App::bind('{YOUR_NAMESPACE}Repositories\PostRepository', '{YOUR_NAMESPACE}Repositories\PostRepositoryEloquent');

And use

public function __construct({YOUR_NAMESPACE}Repositories\PostRepository $repository){
    $this->repository = $repository;
}

Alternatively, you could use the artisan command to do the binding for you.

php artisan make:bindings Cats

Use methods

namespace App\Http\Controllers;

use App\PostRepository;

class PostsController extends BaseController {

    /**
     * @var PostRepository
     */
    protected $repository;

    public function __construct(PostRepository $repository){
        $this->repository = $repository;
    }

    ....
}

Find all results in Repository

$posts = $this->repository->all();

Find all results in Repository with pagination

$posts = $this->repository->paginate($limit = null, $columns = ['*']);

Find by result by id

$post = $this->repository->find($id);

Hiding attributes of the model

$post = $this->repository->hidden(['country_id'])->find($id);

Showing only specific attributes of the model

$post = $this->repository->visible(['id', 'state_id'])->find($id);

Loading the Model relationships

$post = $this->repository->with(['state'])->find($id);

Find by result by field name

$posts = $this->repository->findByField('country_id','15');

Find by result by multiple fields

$posts = $this->repository->findWhere([
    //Default Condition =
    'state_id'=>'10',
    'country_id'=>'15',

    //Custom Condition
    ['columnName1','>','10'],

    //DATE, DAY, MONTH, YEAR
    ['columnName2','DATE','2021-07-02'], //whereDate
    ['columnName3','DATE >=','2021-07-02'], //whereDate with operator

    ['columnName4','IN',['value1','value2']], //whereIn
    ['columnName5','NOTIN',['value1','value2']], //whereNotIn
    ['columnName6','EXIST',''], //whereExists
    
    //HAS, HASMORPH, DOESNTHAVE, DOESNTHAVEMORPH
    ['columnName7','HAS',function($query){}], //whereHas

    //BETWEEN, BETWEENCOLUMNS, NOTBETWEEN, NOTBETWEENCOLUMNS
    ['columnName8','BETWEEN',[10, 100]], //whereBetween
]);

Find by result by multiple values in one field

$posts = $this->repository->findWhereIn('id', [1,2,3,4,5]);

Find by result by excluding multiple values in one field

$posts = $this->repository->findWhereNotIn('id', [6,7,8,9,10]);

Find all using custom scope

$posts = $this->repository->scopeQuery(function($query){
    return $query->orderBy('sort_order','asc');
})->all();

Create new entry in Repository

$post = $this->repository->create( Input::all() );

Update entry in Repository

$post = $this->repository->update( Input::all(), $id );

Delete entry in Repository

$this->repository->delete($id)

Delete entry in Repository by multiple fields

$this->repository->deleteWhere([
    //Default Condition =
    'state_id'=>'10',
    'country_id'=>'15',
])

Create a Criteria

Using the command

php artisan make:criteria MyCriteria

Criteria are a way to change the repository of the query by applying specific conditions according to your needs. You can add multiple Criteria in your repository.

use Prettus\Repository\Contracts\RepositoryInterface;
use Prettus\Repository\Contracts\CriteriaInterface;

class MyCriteria implements CriteriaInterface {

    public function apply($model, RepositoryInterface $repository)
    {
        $model = $model->where('user_id','=', Auth::user()->id );
        return $model;
    }
}

Using the Criteria in a Controller

namespace App\Http\Controllers;

use App\PostRepository;

class PostsController extends BaseController {

    /**
     * @var PostRepository
     */
    protected $repository;

    public function __construct(PostRepository $repository){
        $this->repository = $repository;
    }


    public function index()
    {
        $this->repository->pushCriteria(new MyCriteria1());
        $this->repository->pushCriteria(MyCriteria2::class);
        $posts = $this->repository->all();
		...
    }

}

Getting results from Criteria

$posts = $this->repository->getByCriteria(new MyCriteria());

Setting the default Criteria in Repository

use Prettus\Repository\Eloquent\BaseRepository;

class PostRepository extends BaseRepository {

    public function boot(){
        $this->pushCriteria(new MyCriteria());
        // or
        $this->pushCriteria(AnotherCriteria::class);
        ...
    }

    function model(){
       return "App\\Post";
    }
}

Skip criteria defined in the repository

Use skipCriteria before any other chaining method

$posts = $this->repository->skipCriteria()->all();

Popping criteria

Use popCriteria to remove a criteria

$this->repository->popCriteria(new Criteria1());
// or
$this->repository->popCriteria(Criteria1::class);

Using the RequestCriteria

RequestCriteria is a standard Criteria implementation. It enables filters to perform in the repository from parameters sent in the request.

You can perform a dynamic search, filter the data and customize the queries.

To use the Criteria in your repository, you can add a new criteria in the boot method of your repository, or directly use in your controller, in order to filter out only a few requests.

热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap