美文网首页LaravelormLaravel开发实践
通过Eloquent实现Repository模式

通过Eloquent实现Repository模式

作者: 小聪明李良才 | 来源:发表于2016-12-06 11:43 被阅读1350次

    胖胖的Eloquent

    Eloquent采用了ActiveRecord的模式,这也让Eloquent招致了好多批评,让我们去看现在Eloquent/Model.php文件, 该文件已经有3500多行,此时的Model集成了太多的功能了,一个新人很难短时去理解Model并去很好的使用了,目前Eloquent/Model中主要混合了4个功能:

    1. Domain Model(包括了data model和领域逻辑)
    2. Row Data Gateway(例如save,delete等数据持久化操作)
    3. Table data gateway(各种find方法)
    4. Factory(新建model)

    上面介绍的几种ORM设计模式,可以去之前的文章查看:orm 系列 之 常用设计模式

    我们可以看到Model中混合了各种模式,这就要求使用者在使用的时候清楚的知道怎么使用,这里的清楚知道怎么用是指根据SOILD原则,优雅的使用Model,本文的目的就是帮助Model的使用者达成优雅的目标。

    那理想的Model使用是什么样子的呢?我们希望Model的使用不是ActiveRecord,而是较为清晰的DataMapper模式,能够让domain model和database解耦,然后由DataMapper来完成映射工作,更具体点,我们希望的是像clean architecture中定义的架构一样,内层是Domain Model,外面是Domain Services,Domain Services又可以具体分为:

    • Repositories

      服务领域对象的存取,如果后端是数据库,就是负责将数据从数据库中取出,将对象存入数据库。

    • Factories

      负责对象的创建。

    • Services

      具体的业务逻辑,通过调用多个对象和其他服务来完成一个业务目标。

    由此实现很好的解耦和关注点分离,更具体的关注clean architecture可以查看简书专题:clean architecture.

    Eloquent拆解

    讲述了一些方法论后,我们来动手实作一下

    talk is cheap, show me the code

    第一步,我们定义一个member表

    php artisan make:migration MemberCreate
    

    第二步,编写表定义

    Schema::create('members',function(Blueprint $table){
        $table->increments('id');
        $table->string('login_name');
        $table->string('display_name');
        $table->integer('posts')->unsigned();
    });
    

    第三步,执行migration

    php artisan migrate
    

    第四步,生成model文件

    php make:model Member
    

    下面开始定义一些接口

    The Member Model Interface

    interface MemberInterface
    {
        public function getID();
        public function getLoginName();
        public function getDisplayName();   
        public function getPostCount();
        public function incrementPostCount();
        public function decrementPostCount();
    }
    

    The Eloquent Member Model Implementation

    class Member extends Model implements MemberInterface
    {
        const ATTR_DISPLAY_NAME = ‘display_name’;
        const ATTR_LOGIN_NAME = ‘login_name’;
        const ATTR_POST_COUNT = ‘posts’;
     
        protected $fillable = [
            self::ATTR_LOGIN_NAME,
            self::ATTR_DISPLAY_NAME
        ];
        public function getID()
        {
            return $this->getKey()
        }
        public function getLoginName()
        {
            return $this->{self::ATTR_LOGIN_NAME};
        }
     
        public function getDisplayName()
        {
            return $this->{self::ATTR_DISPLAY_NAME};
        }
     
        public function getPostCount()
        {
            return $this->{self::ATTR_POST_COUNT};
        }
     
        public function incrementPostCount()
        {
            $this->{self::ATTR_POST_COUNT}++;
        }
        public function decrementPostCount()
        {
            if ($this->getPostCount() > 0) {
                $this->{self::ATTR_POST_COUNT}--;
            }
        }
    }
    

    The Member Repository Interface

    interface MemberRepositoryInterface
    {
       public function find($id);
       public function findTopPosters($count = 10);
       public function save(MemberInterface $member);
    }
    

    The Eloquent Member Repository Implementation

    class EloquentMemberRepository implements MemberRepositoryInterface {
        /** @var  Member */
        protected $model;
    
        /**
         * EloquentMemberRepository constructor.
         *
         * @param \App\Member $model
         */
        public function __construct( Member $model )
        {
            $this->model = $model;
        }
    
        public function find( $id )
        {
            return $this->model->find($id);
        }
    
        /**
         * @param int $count
         *
         * @return \Illuminate\Support\Collection
         */
        public function findTopPosters( $count = 10 )
        {
            return $this->model
                ->orderBy(($this->model)::ATTR_POST_COUNT, 'DESC')
                ->take($count)
                ->get();
        }
    
        public function save( MemberInterface $member )
        {
            $member->save();
            /*
          注意:此处我们接口声明上是 MemberInterface ,这个是普适的规则
            但是此处的 Eloquent 实现是基于 Eloquent Model的,因此假设 传入的
            MemberInterface 实现了 save 方法
          */
        }
    }
    

    基本使用

    DemonstrationController
    {
        public function createPost(MemberRepositoryInterface $repository)
        {
            // validate request, create the post, and...
            $member = Auth::user()->member();
            $member->incrementPostCount();
            $respository->save($member);
        }
        public function deletePost(MemberRepositoryInterface $repository)
        {
            // validate request, delete the post, and...
            $member = Auth::user()->member();
            $member->decrementPostCount();
            $respository->save($member);
         }
        public function dashboard(MemberRespositoryInterface $repository)
        {
            $members = $repository->findTopPosters(20);
            return view('dashboard', compact('members'));
        }
    }
    

    使用的时候我们看到了好的方式,那如果我们没有定义repository和interface,会怎么样呢?

    DemonstrationController
    {
        public function createPost()
        {
            // validate request, create the post, and...
            $member = Auth::user()->getMember();
            $member->posts++;
            $member->save();
        }
        public function deletePost()
        {
            // validate request, delete the post, and...
            $member = Auth::user()->getMember();
            if ($member->posts > 0) {
                $member->posts--;
                $member->save();
            }
        }
        public function dashboard()
        {
            $members = Member::orderBy('posts', 'DESC')->take(20)->get(); 
            return view('dashboard', compact('members'));
        }
    }
    

    上面简单的业务逻辑posts不能小于0,都没有很好的封装,如果上面我们一些增加和减少的功能和save封装到一起呢?

    DemonstrationController
    {
        public function createPost()
        {
            // validate request, create the post, and...
            $member = Auth::user()->member();
            $member->incrementPostCount();
        }
        public function deletePost()
        {
            // validate request, delete the post, and...
            $member = Auth::user()->member();
            $member->decrementPostCount();
        }
    }
    class Member extends Model implements MemberInterface
    {
        //...
        
      
        public function incrementPostCount()
        {
            $this->{self::ATTR_POST_COUNT}++;
            $this->save();
        }
        public function decrementPostCount()
        {
            if ($this->getPostCount() > 0) {
                $this->{self::ATTR_POST_COUNT}--;
                $this->save();
            }
        }
        
        // ...
    }
    

    这样做主要有两个问题

    1. 如果我们将Model的实现由Eloquen转换为其他呢?这将会使应用出错
    2. 我们每个更改都是执行一个sql语句,严重浪费,我们完全可以做完更改后,统一一次update

    通过上面的对比,我们更能发现使用Repository和Interface的好处,能让我们更好的实现关注点分离,下面我们会更深入的讨论一些问题:包括Collections, Relations, Eager Loading, 和 Schema Changes。

    Eloquent进阶

    首先介绍collection的问题,看代码

    class FooController
    {
       public function bar(PostRepositoryInterface $repository)
       {
          $posts = $repository->findActivePosts();
          $posts->load('author');
       }
    }
    

    上面的代码中,虽然我们使用的type hint表明使用的repository是PostRepositoryInterface,但是方法findActivePosts返回的collection显然是跟Eloquent耦合的Eloquent\Collection,那怎么解决这个问题呢?有以下几个方案

    1. findActivePosts返回�Collection,而不是Eloquent\Collection,避免在Repository之外使用Eloquent相关的功能
    2. 通过custom collections方法,返回自定义的collection

    下面介绍第二个议题Eager Loading

    还是看代码

    class FooController
    {
       public function bar(PostRepositoryInterface $repository)
       {
          $posts = $repository->findActivePosts(['author']);
       }
    }
    

    上面的代码通过参数['author']的传入,将eager loading的操作封装在了findActivePosts之内,但是这样子做,反而让调用方必须知道实现细节,即本来是功能上的优化,通过eager loading来解决N+1问题的方案,变为了业务需要知道的业务的逻辑了,明显是不合理的。

    更可怕的时候,你可能会希望通过传入参数让findActivePosts实现更多的功能,于是变为了下面的函数findActivePostsInDateRange($start, $end, $eagerLoading = null),我们看到随着项目复杂度的提升,我们不得不通过通过参数来满足更多的需求,但是这也使得接口变得更复杂,功能更多,到最后我们不得不面对各种ugly的代码,那面对Eager Loading我们到底应该怎么办呢?下面给出一个建议:

    在提供非eager loading的方法同时,提供一个eager loading的方法。这可能会被人说:这也不是让用户知道了实现细节了嘛。是的,这方法是一个性能和使用上的妥协。

    最后介绍Relations,看到代码

    interface MemberInterface
    {
       public function getID();
       public function getLoginName();
       public function getDisplayName();   
       public function getPostCount();
       public function incrementPostCount();
       public function decrementPostCount();
       public function getPosts();
       public function getFavoritePosts();
    }
    class Member extends Model implements MemberInterface
    {
       ...
    
       public function posts()
       {
          return $this->hasMany(Post::class);
       }
    
       public function getPosts()
       {
           return $this->posts;
       }
    
       public function getFavoritePosts()
       {
           // I think this will work!
           return $this->posts()
                       ->newQuery()
                       ->whereHas('favorites', function($q) {
                            $q->where(Favorite::ATTR_MEMBER_ID, $this->getID()); 
                         })->get();
       }
    
       ...
    }
    

    我们没有办法将relation Method设置为protect或者private(这样设置的目的是让外面不使用,限制使用范围),但是这样子会导致想whereHas这种方法执行不成功。

    此处还注意到一个问题,我们此时使用的posts是表示relation,但是之前是member的一个字段,明显冲突了,我们需要修改字段名,从postspost_count,因为我们之前使用了常量来定义属性,因此只需要下面一行代码就解决问题了:

    const ATTR_POST_COUNT = ‘post_count’;
    

    总结

    介绍了这么多,我们解决了一个核心问题:因为Eloquent的功能耦合,我们应该正确的使用它,Eloquent的ActiveRecord模式可以让我们非常容易的实现DataMapper,根据Clean architecture的定义,我们将domain services分为了Repositories,Factories,Services,实现了关注点分离。

    但是到目前,还有一个问题没有解决,那就是通过Repository,我们很难实先Eloquent/Builder那样丰富的查询功能,我们不得不每次新增一个查询条件,就去新增接口或者参数,不慎其烦,就像之前的findActivePostsInDateRange方法一样丑陋,那到底有什么办法解决呢?尽情期待下一篇内容,Repository的实作。

    参考

    Separation of Concerns with Laravel’s Eloquent Part 1: An Introduction

    相关文章

      网友评论

      • Laragh:为嘛不用l5-repository
        小聪明李良才: @xhh110 可以看我个人主页的,已经写了篇介绍的了☺
        Laragh:@超级个体颛顼 期待 正在研究。。。。
        小聪明李良才: @xhh110 嗯下面一篇介绍的就是这个库☺
      • ninja911:期待作者的下一期
        小聪明李良才: @ninja911 已更新可以在我主页看到
      • AndZONE:期待下一篇
        小聪明李良才: @汪帅 已更新可以看我主页的
      • oraoto:用ActiveRecord实现Repository,只能做到集中查询逻辑,让代码更清晰,Repository的最大好处(和数据持久化解耦)却没了(或很难实现,因为底层的model已经和数据库耦合了)
        小聪明李良才: @oraoto 这个就要看你返回什么了,在repository的时候你可以返回一个对象接口,具体实现是EloquentModel,但是所有的决策都是权衡,如果你觉得自己不会放弃eloquent,那直接返回EloquentModel的类型声明也没事,至于你说的在repository外使用独有的Eloquent方法,或者靠使用者自己约束,或者在返回类型上约束
        oraoto:@超级个体颛顼 不管查询委托给什么,最后还是返回了ActiveRecord对象,然后又可以通过ActiveRecord对象的关系去查询更多的数据(也不管底层是Builder还是其他)。所以最后还是AR负责数据查询,Repository只是一些复杂、有特殊意义的查询的集合。这种用法挺好的。如果把AR类当做集合,而类的实例是集合中的一个元素,AR看起来就是一个仓库,那我把你的Repository里的方法都变成AR类里静态方法是不是能达到同样的效果。
        小聪明李良才:@oraoto 个人看代码的感受,Eloquet中其实具体的数据库查询操作都是委托给了Eloquet/Builder,所以在实现Repository的时候,Eloquent/Model就只负责数据部分,然后具体的数据查询操作就给了Repository,然后底层实现是委托给了Eloquet/Builder,所以Eloquent实现的ActiveRecord是很耦合,但是如果我们使用得当的话,也能实现很好的关注点分离,程序可扩展,模式再好,用对才是关键
      • w暗暗啊w:不错!!!
        小聪明李良才: @w暗暗啊w 谢谢☺
      • 该叶无法找到:哎呀沙发没了…赞:+1:
      • Questocat:赞
        小聪明李良才: @鲁男子 谢谢☺

      本文标题:通过Eloquent实现Repository模式

      本文链接:https://www.haomeiwen.com/subject/pqqrmttx.html