M
M
Maxim Zolotoy2020-06-10 20:44:42
PHP
Maxim Zolotoy, 2020-06-10 20:44:42

Is this solution of injection normal from an architectural point of view?

I'm just getting started with OOP. Can you please let me know if this is normal or is it different?
Here I have a repository class for products on the site

class ProductRepository
  {
    private $product; // Сюда попадает App\Entities\Product
    
    public function __construct($product)
    {
      $this->product = $product;
    }
    
    public function get($id)
    {
      $data = DB::selectOne('SELECT * FROM products WHERE id = ?', [$id]);
      
      if ($data) {
        $data = $this->joinDependencies($data);
        return new $this->product($data); // Тут я создаю новый объект сущности, заполненный данными и отдаю
      }
      
      return null;
    }
  }


And there is an entry in the service container
. It confuses me that just the name is transferred here, although in other places a ready-made object is injected, but this does not suit me here, since I will need to create a new one inside.

$this->app->singleton(ProductRepository::class, function () {
    return new ProductRepository(Product::class);
});


Am I doing the right thing or are there other better ways?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question