O
O
ortsuev332019-08-01 09:33:09
Laravel
ortsuev33, 2019-08-01 09:33:09

What is the point of passing data in this way?

use Corp\Portfolio;

class PortfoliosRepository extends Repository {
  
  public function __construct(Portfolio $portfolio) {
    $this->model = $portfolio;
  }

if you can just $this->model=Portfolio::all();
In pre-processing in another file? (i.e. preparation of methods for yourself?)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2019-08-01
@ortsuev33

I'm talking about the fact that the data is passed through the constructor. After all, you can simply define them in the code itself of the same file
In the constructor in this case are passed to the data, and the object that will build queries. This is the same repository class - it encapsulates queries to the database, but it uses Eloquent models.
class PortfoliosRepository extends Repository {
  public function __construct(Portfolio $portfolio) {
    $this->model = $portfolio;
  }

  // Этот метод, скорее всего, есть в базовом классе
  public function find(int $id): ?Portfolio
  {
    return $this->model->find($id);
  }

  // А это пример инкапсуляции сложной логики
  public function featured(): Collection
  {
    return $this->model
      ->with(['some', 'relations'])
      ->where('field', 'value')
      ->orWhere('other_field', 'value')
      ->orderBy('created_at')
      ->limit(42)
      ->get()
      ->each
      ->append('mutated_attribute');
  }
}

This class is used like this:
$repository = new PortfoliosRepository(
  new Portfolio // <- не какое-то существующее портфолио из БД, а "пустой" объект
);

$repository->featured();

D
Dmitry, 2019-08-01
@dimsog

Using public property is good only for some DTO, in other cases it will crash. It is better to use data passing in the constructor or setters for this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question