0

What it is the best way to implement a dependency injection, this way:

new App\Controllers\HomeController();

Class HomeController

use App\Views\HomeView;

class HomeController {

private $view;

public function __construct() {
    $this->view = new HomeView();

or this way:

new App\Controllers\HomeController(new App\Views\HomeView());
Isabella
  • 15
  • 3

2 Answers2

0

Dependency injections is usually (if not always) done via a IoC (Inversion of control) - container. The container, or rather it's dependency injection logic takes care of creating the objects and through some magic fetches all the parameters expected to be added and creates them, also from the containers dependency injection logic.

What you are doing is rather just creating new objects. You could do that either way you wish, but personally I would probably pass the view through the constructor.

If you wish to read more about dependency injection and containers, id refer to the wiki entry about it.
You can also take a look at one of my naive implementations of a dependency container using php reflections here if you wish!

Jite
  • 5,761
  • 2
  • 23
  • 37
0

Samples you've provided reflect totally different approaches (I've left class naming same as you have):

// App/Controllers/HomeController.php
use App\Views\HomeView;

class HomeController {

    private $view;

    public function __construct() {
        $this->view = new HomeView();
    }
}

This is not dependency injection, you create the stuff your class depends on inside the class.

Compare to:

// App/Controllers/HomeController.php
use App\Views\HomeView;

class HomeController {

    private $view;

    public function __construct(HomeView $view) {
        $this->view = $view;
    }
}

This is actually dependecy injection: whatever your class needs is created outside of the class and passed to it via constructor (in this particular case).

Some tool (dependency injection container) may or may not be used to manage the dependencies depending on your case.

To get some more details please see the article https://martinfowler.com/articles/injection.html by Martin Fowler and search here on SO - the topic is extensively covered (What is dependency injection?, What is Dependency Injection?, When to use Dependency Injection).

xmike
  • 1,029
  • 9
  • 14