質問

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