I am trying to implement the repository pattern using Laravel. I can understand the advantages of having interfaces to abstract the data storage.

But what about the objects returned by the methods defined in the interface. Should they also be defined in some kind of abstract class?

For instance:

class UserRepository implements UserInterface {
    protected $user;

    public function __construct(Model $user)
    {
        $this->user = $user;
    }

    public function find($userId)
    {
        return $this->user->find($userId);
    }
}

by doing this in my controller:

$user = UserRepository::find(1);
$user->name

am I breaking the design pattern?

有帮助吗?

解决方案

Short answer: Yes.

Long answer: according to the Dependency Inversion Principle you always have to depend on abstractions not concretions. If one day you need to change the implementation of that Model, you'll have to change that repository class, also going against the Open-Closed Principle.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top