D
D
darksladen2018-05-04 13:16:42
Laravel
darksladen, 2018-05-04 13:16:42

Where to take out the sampling logic?

Tell me, where is it better to take out various checks for data sampling? Let's say there is a site with ads and you need to get the ads posted by the user, as well as which he used .. One of the options, with the most popular being 2 lines in the controller:

$selling = Ads::where('owner_id', 23);
$purchases = Ads::where('buyer_id', 23);

But I understand that this is a bad solution for more or less complex projects, you need to put such logic somewhere. Or should repositories do this? Please tell me the best way to do this..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D3lphi, 2018-05-04
@darksladen

All work with the database should be done in repositories.
The repository works with entities, so if you use active record ORM, you will need to create an entity from the ar model and return it from the repository. We do not allow the connection to the database to "walk" around the project. Entity is an ordinary popo in which there is no logic, but there is only a set of fields, getters, and methods for updating the state.
For example:

class EloquentUserRepository implements UserRepository
{
    public function findBySomething(string $something): ?UserEntity
    {
          $user = User::where('something', $something)->first();

          if ($user !== null) {
              return new UserEntity($user->id, $user->something);
          }

          return null;
    }
}

The right decision. It is better to abandon eloquent and take doctrine if the project requires a serious ORM.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question