M
M
Muhammad2015-04-19 15:03:31
PHP
Muhammad, 2015-04-19 15:03:31

Where is the "Repository" pattern used?

Good afternoon. I have heard many times about the Repository pattern and how good it is, but I still don’t understand where it can be used. Could someone provide a couple of examples of its use?
PS: did I understand correctly that a repository is a class to which an object and a name are passed under which this object will be stored and with the help of this name the object can subsequently be obtained?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-04-20
@muhammad_97

The repository pattern is used to isolate data storage logic. For example:

interface UserRepository {
    function getUser($id);
    function getUsersWhichSatisfyMyCustomBuisnessRulecs(BuisnessRules $rules);
    function saveUser(User $user);
}

class InMemoryUserRepository implements UserRepository {
    private $users = [];

    function getUser($id) {
         return isset($this->users[$id]) ? 
             $this->users[$id] : null;
    }

    function getUsersWhichSatisfyMyCustomBuisnessRulecs(BuisnessRules $rules) {
         return array_filter($this->users, function (User $user) use ($rules) {
               return $user->isSatisfyRule($rules->getSomeRule());
         }
    }
    function saveUser(User $user) {
        $this->users[$user->getId()] = $user;
    }
}

What this example shows:
- that the repository for the application is primarily an interface, the implementation of which can be changed at any time. Which allows us to change the storage for individual entities at will. Also, InMemoryRepository is often used in unit testing (although usually these are interface mocks).
- that there is no rigid binding to implementation. You can use plain sql inside the repository, data mapper, active record, associative arrays, files... you get the idea. Implement the main interface.
- the repository allows you to build the architecture of the application without linking everything to the data storage logic. In this way, we organize a weak coupling of the system and adhere to the principle of single responsibility.
martinfowler.com/eaaCatalog/repository.html

A
Alex, 2015-04-19
@mr_ko

Here it seems to be available habrahabr.ru/post/248505

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question