在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):andersao/l5-repository开源软件地址(OpenSource Url):https://github.com/andersao/l5-repository开源编程语言(OpenSource Language):PHP 100.0%开源软件介绍(OpenSource Introduction):Laravel 5 RepositoriesLaravel 5 Repositories is used to abstract the data layer, making our application more flexible to maintain. 1.0.* / 2.0.*See versions:2.0 / 2.1Migrate to:You want to know a little more about the Repository pattern? Read this great article. Table of ContentsInstallationComposerExecute the following command to get the latest version of the package:
Laravel>= laravel5.5ServiceProvider will be attached automatically OtherIn your '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" MethodsPrettus\Repository\Contracts\RepositoryInterface
Prettus\Repository\Contracts\RepositoryCriteriaInterface
Prettus\Repository\Contracts\CacheableInterface
Prettus\Repository\Contracts\PresenterInterface
Prettus\Repository\Contracts\Presentable
Prettus\Repository\Contracts\CriteriaInterface
Prettus\Repository\Contracts\Transformable
UsageCreate a ModelCreate 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 Repositorynamespace App;
use Prettus\Repository\Eloquent\BaseRepository;
class PostRepository extends BaseRepository {
/**
* Specify Model class name
*
* @return string
*/
function model()
{
return "App\\Post";
}
} GeneratorsCreate your repositories easily through the generator. ConfigYou 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 ...
'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 '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',
]
] CommandsTo generate everything you need for your Model, run this command:
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 To generate a repository for your Post model, use the following command
To generate a repository for your Post model with Blog namespace, use the following command
Added fields that are fillable
To add validations rules directly with your command you need to pass the
The command will also create your basic RESTfull controller so just add this line into your 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 methodsnamespace 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 CriteriaUsing the command
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 Controllernamespace 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 repositoryUse $posts = $this->repository->skipCriteria()->all(); Popping criteriaUse $this->repository->popCriteria(new Criteria1());
// or
$this->repository->popCriteria(Criteria1::class); Using the RequestCriteriaRequestCriteria 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. |