zerospam/laravel-cacheable-repository
Composer 安装命令:
composer require zerospam/laravel-cacheable-repository
包简介
Laravel 5 - Repositories to the database layer
README 文档
README
Laravel 5 Repositories is used to abstract the data layer, making our application more flexible to maintain.
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 zerospam/laravel-cacheable-repository
Laravel
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
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 = [*])
- create(array $attributes)
- update(array $attributes, $id)
- updateOrCreate(array $attributes, array $values = [])
- delete($id)
- 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();
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)
- getCacheMinutes()
- skipCache($status = true)
Prettus\Repository\Contracts\CriteriaInterface
- apply($model, RepositoryInterface $repository);
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";
}
}
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
['columnName','>','10']
]);
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)
Create a Criteria
Using the command
php artisan make:criteria My
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.
Enabling in your Repository
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
class PostRepository extends BaseRepository {
/**
* @var array
*/
protected $fieldSearchable = [
'name',
'email'
];
public function boot(){
$this->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
...
}
function model(){
return "App\\Post";
}
}
Remember, you need to define which fields from the model can be searchable.
In your repository set $fieldSearchable with the name of the fields to be searchable or a relation to fields.
protected $fieldSearchable = [
'name',
'email',
'product.name'
];
You can set the type of condition which will be used to perform the query, the default condition is "="
protected $fieldSearchable = [
'name'=>'like',
'email', // Default Condition "="
'your_field'=>'condition'
];
Enabling in your Controller
public function index()
{
$this->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
$posts = $this->repository->all();
...
}
Example the Criteria
Request all data without filter by request
http://prettus.local/users
[
{
"id": 1,
"name": "John Doe",
"email": "john@gmail.com",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00"
},
{
"id": 2,
"name": "Lorem Ipsum",
"email": "lorem@ipsum.com",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00"
},
{
"id": 3,
"name": "Laravel",
"email": "laravel@gmail.com",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00"
}
]
Conducting research in the repository
http://prettus.local/users?search=John%20Doe
or
http://prettus.local/users?search=John&searchFields=name:like
or
http://prettus.local/users?search=john@gmail.com&searchFields=email:=
or
http://prettus.local/users?search=name:John Doe;email:john@gmail.com
or
http://prettus.local/users?search=name:John;email:john@gmail.com&searchFields=name:like;email:=
[
{
"id": 1,
"name": "John Doe",
"email": "john@gmail.com",
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00"
}
]
Filtering fields
http://prettus.local/users?filter=id;name
[
{
"id": 1,
"name": "John Doe"
},
{
"id": 2,
"name": "Lorem Ipsum"
},
{
"id": 3,
"name": "Laravel"
}
]
Sorting the results
http://prettus.local/users?filter=id;name&orderBy=id&sortedBy=desc
[
{
"id": 3,
"name": "Laravel"
},
{
"id": 2,
"name": "Lorem Ipsum"
},
{
"id": 1,
"name": "John Doe"
}
]
Sorting through related tables
http://prettus.local/users?orderBy=posts|title&sortedBy=desc
Query will have something like this
...
INNER JOIN posts ON users.post_id = posts.id
...
ORDER BY title
...
http://prettus.local/users?orderBy=posts:custom_id|posts.title&sortedBy=desc
Query will have something like this
...
INNER JOIN posts ON users.custom_id = posts.id
...
ORDER BY posts.title
...
Add relationship
http://prettus.local/users?with=groups
Overwrite params name
You can change the name of the parameters in the configuration file config/repository.php
Cache
Add a layer of cache easily to your repository
Cache Usage
Implements the interface CacheableInterface and use CacheableRepository Trait.
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Contracts\CacheableInterface;
use Prettus\Repository\Traits\CacheableRepository;
class PostRepository extends BaseRepository implements CacheableInterface {
use CacheableRepository;
...
}
Done , done that your repository will be cached , and the repository cache is cleared whenever an item is created, modified or deleted.
Cache Config
You can change the cache settings in the file config/repository.php and also directly on your repository.
config/repository.php
'cache'=>[
//Enable or disable cache repositories
'enabled' => true,
//Lifetime of cache
'minutes' => 30,
//Repository Cache, implementation Illuminate\Contracts\Cache\Repository
'repository'=> 'cache',
//Sets clearing the cache
'clean' => [
//Enable, disable clearing the cache on changes
'enabled' => true,
'on' => [
//Enable, disable clearing the cache when you create an item
'create'=>true,
//Enable, disable clearing the cache when upgrading an item
'update'=>true,
//Enable, disable clearing the cache when you delete an item
'delete'=>true,
]
],
'params' => [
//Request parameter that will be used to bypass the cache repository
'skipCache'=>'skipCache'
],
'allowed'=>[
//Allow caching only for some methods
'only' =>null,
//Allow caching for all available methods, except
'except'=>null
],
],
It is possible to override these settings directly in the repository.
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Contracts\CacheableInterface;
use Prettus\Repository\Traits\CacheableRepository;
class PostRepository extends BaseRepository implements CacheableInterface {
// Setting the lifetime of the cache to a repository specifically
protected $cacheMinutes = 90;
protected $cacheOnly = ['all', ...];
//or
protected $cacheExcept = ['find', ...];
use CacheableRepository;
...
}
The cacheable methods are : all, paginate, find, findByField, findWhere, getByCriteria
zerospam/laravel-cacheable-repository 适用场景与选型建议
zerospam/laravel-cacheable-repository 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.18k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2017 年 02 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「cache」 「repository」 「model」 「laravel」 「eloquent」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 zerospam/laravel-cacheable-repository 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 zerospam/laravel-cacheable-repository 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 zerospam/laravel-cacheable-repository 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
repository php library
A package for automatically encrypting and decrypting Eloquent attributes in Laravel 5.5+, based on configuration settings.
Interfaces for web resource models and services to retrieve and create them
This package provides an Address Model, Migration and Factory. It also provides the traits HasBillingAddres and HasPublicAddress
Structure for the Laravel Service-Repository Pattern
The YADM migrations
统计信息
- 总下载量: 3.18k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 8
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2017-02-10