Proper Repository Pattern Design in PHP?

后端 未结 11 779
天涯浪人
天涯浪人 2020-11-29 14:22

Preface: I\'m attempting to use the repository pattern in an MVC architecture with relational databases.

I\'ve recently started learning TDD in PHP, and I\'

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 14:54

    I'll add a bit on this as I am currently trying to grasp all of this myself.

    #1 and 2

    This is a perfect place for your ORM to do the heavy lifting. If you are using a model that implements some kind of ORM, you can just use it's methods to take care of these things. Make your own orderBy functions that implement the Eloquent methods if you need to. Using Eloquent for instance:

    class DbUserRepository implements UserRepositoryInterface
    {
        public function findAll()
        {
            return User::all();
        }
    
        public function get(Array $columns)
        {
           return User::select($columns);
        }
    

    What you seem to be looking for is an ORM. No reason your Repository can't be based around one. This would require User extend eloquent, but I personally don't see that as a problem.

    If you do however want to avoid an ORM, you would then have to "roll your own" to get what you're looking for.

    #3

    Interfaces aren't supposed be hard and fast requirements. Something can implement an interface and add to it. What it can't do is fail to implement a required function of that interface. You can also extend interfaces like classes to keep things DRY.

    That said, I'm just starting to get a grasp, but these realizations have helped me.

提交回复
热议问题