I'm trying to wrap my head around the dependency injection concept in PHP. I understand the basic principle where dependency injection is used to "pre-load" all necessary parameters, functions, objects.. whatever is need for an operation to run.
However when I try to implement it on a test MVC I get the feeling I am not doing anything but shifting data around.
I wrote a small example of how I've been doing it. So if anybody would be so kind to tell me what im doing wrong.
PS. I know about the dependency injection container that frameworks usually apply, however there would be no point in using something like that if I am unable to grasp the basics of it.
Example:
<?php
class database_test
{
public function __construct($DB_con_info)
{
try {
$dsn = "mysql:host=" . $DB_con_info['host'] .
";dbname=" . $DB_con_info['dbname'] .
";charset=" . $DB_con_info['charset'];
echo 'database connection set -> ';
$this->dbc = new PDO ($dsn, $DB_con_info['username'], $DB_con_info['password']);
$this->dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "conn failed msg : " . $e->fetMessage();
}
}
}
class model_interface extends database_test
{
protected $dbc;
protected $DB_con_info = array(
'driver' => 'mysql',
'host' => 'localhost',
'dbname' => 'mvc_db',
'username' => 'root',
'password' => '',
'charset' => 'utf8mb4'
);
//depende_injection
public function __construct()
{
parent::__construct($this->DB_con_info);
echo 'model_interface set -> ';
}
public function __destruct()
{
$this->dbc = null;
}
public function add($username, $last_name)
{
$sth = $this->dbc->prepare('INSERT INTO test (name, last_name ) VALUES (?,?)');
$sth->execute([$username, $last_name]);
}
}
class controller_test
{
protected function __construct($name)
{
$this->view = new view();
$this->model = $this->loadModel($name);
}
protected function loadModel($model)
{
//require the php file with the model class (test_model) in it
require_once 'models/' . $model . '_model.php';
//$model= test_model;
$model = $model . '_model';
//return new object of class test_model
return new $model();
}
}
class test_model extends model_interface
{
private $model_interface_functions;
//depende_injection
public function __construct()
{
$this->model_interface_functions = new model_interface;
echo 'model_interface_functions set ->';
}
public function __destruct()
{
$this->model_interface_functions = null;
}
public function test2()
{
$name = 'name';
$last_name = 'last_name';
$this->model_interface_functions->add($name, $last_name);
}
}
class Test extends controller_test
{
protected $model;
protected $view;
//depende_injection
public function __construct()
{
echo 'setting depende_injection<br>';
parent::__construct('test');
echo 'all dependencies set ->';
}
public function test()
{
echo 'test controller <br>';
$this->model->test2();
}
public function __destruct()
{
$this->model = null;
$this->view = null;
}
public function index()
{
$this->view->render('test', 'index');
}
}