I just learned about dependency injection/dependency injection containers, and I realize that the controller in my MVC web application is hard to test.
My original controller class:
class Controller
{
protected $db;
private $article;
private $nav;
public function __construct($db)
{
$this->db = $db;
$this->article = new Article($this->db);
$this->nav = new Nav($this->db);
}
public function render($template)
{
var_dump($this->article->getRow());
var_dump($this->nav->getRows());
}
}
This is my test using DI/DIC in my MVC app:
Controller
class Controller
{
private $container;
public function __construct()
{
}
public function render($container,$template)
{
$this->container = $container;
var_dump($this->container->getArticle($url = 'home'));
var_dump($this->container->getNav());
}
}
Container: holds all objects which generate data from the database
class Container
{
protected $db;
private $article;
private $nav;
public function __construct($db)
{
$this->db = $db;
}
public function setArticle()
{
if (is_null($this->article))
{
$this->article = new Article($this->db);
}
return $this->article;
}
public function setNav()
{
if (is_null($this->nav))
{
$this->nav = new Nav($this->db);
}
return $this->nav;
}
public function getArticle($url)
{
return $this->setArticle()->getRow($url);
}
public function getNav()
{
return $this->setNav()->getRows();
}
}
Models
class Article
{
public function __construct($db)
{
}
public function getRow($url)
{
return "row 1";
}
}
class nav
{
public function __construct($db)
{
}
public function getRows()
{
return "rows nav";
}
}
Usage
$db = 'pdo connection';
$template = 'template.phtml';
$container = new Container($db);
$controller = new Controller();
$controller->render($container,$template);
Questions:
- Am I doing it correctly or not?
- Do the improved
Controller
andContainer
above make sense to you if you were a developer going to pick up this application's development? - Do I need any interfaces or traits as part of the app? If so, why?
controller is hard to test because it instantiates the objects
but I have reworked on it if you read further down my post. thanks! \$\endgroup\$Controller
, duh! :/ Gufran's answer still stands IMHO. YourController
shouldn't know about theContainer
. I'm not familiar with PHP dependency injection frameworks, but when using Spring (Java), objects instantiated by the DI container do not depend on it. \$\endgroup\$