Lumen Repository(仓储)

在 Laravel 5 中使用 Repository 模式实现业务逻辑和数据访问的分离:http://laravelacademy.org/post/3063.html

Eloquent: 集合:https://d.laravel-china.org/docs/5.3/eloquent-collections

集合:https://d.laravel-china.org/docs/5.3/collections

Laravel & Lumen之Eloquent ORM使用速查-基础部分:https://segmentfault.com/a/1190000005792671

Laravel & Lumen之Eloquent ORM使用速查-进阶部分:https://segmentfault.com/a/1190000005792708

Laravel & Lumen之Eloquent ORM使用速查-高级部分:https://segmentfault.com/a/1190000005792734

Lumen 进阶之数据库交互,Eloquent ORM,Facades,Collection:http://blog.gxxsite.com/lumen-advance-database-interaction/

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

简书这篇讲得很透彻:https://www.jianshu.com/p/dcaaf801c294

这篇也很不错:http://oomusou.io/laravel/laravel-architecture/

实例讲解

先通过migrations建user_log表之后,

使用migrations:http://www.cnblogs.com/cxscode/p/8371789.html

运行下面语句

php artisan make:repository UserLog

  

此时会创建:

app/Models/UserLog.php //对应Model

app/Repositories/UserLogRepository.php  //对应仓储类接口

app/Repositories/UserLogRepositoryEloquent.php //对应仓储类

app/Models/UserLog.php

class UserLog extends Model implements Transformable
{
    use TransformableTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        //       'id',
        'user_id',
        'status',
        'type',
//       'deleted_at',
//       'created_at',
//       'updated_at',
    ];

    protected $table = 'user_log';

    protected $primaryKey = 'id';

}

$fillable默认是空数组,需要补填一些增删改查要操作的字段,$table(表名)和$primaryKey(主键)一般没有,最好自己补全一下

app/Repositories/UserLogRepository.php

interface UserLogRepository extends RepositoryInterface
{
    //
}

一般也是一个空接口,可以根据需求加入需要实现的接口

app/Repositories/UserLogRepositoryEloquent.php

class UserLogRepositoryEloquent extends BaseRepository implements AddressRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Address::class;
    }

    

    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }
    
}

默认有一个model获取方法和一个boot启动方法,可以把仓储做为控制器和Model的中间层,可以实现一些方法,控制器调仓储,仓储调Model

原文地址:https://www.cnblogs.com/cxscode/p/8361446.html