php - 在 PHP 项目中设置依赖注入
问题描述
我正试图围绕 PHP 中的依赖注入概念。我了解依赖注入用于“预加载”所有必要参数、函数、对象的基本原理。运行操作所需的一切。
但是,当我尝试在测试 MVC 上实现它时,我感觉除了移动数据之外我什么也没做。
我写了一个小例子来说明我是如何做到的。因此,如果有人愿意告诉我我做错了什么。
PS。我知道框架通常应用的依赖注入容器,但是如果我无法掌握它的基础知识,那么使用类似的东西就没有意义了。
例子:
<?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');
}
}
解决方案
推荐阅读
- python - 如何检查 QlistWidget 中的项目并在 python pyqt5 中的选定项目上运行函数
- javascript - 如何检测 iframe 是否接受创建的 blob url 作为 iframe 的 src
- javascript - 如何将此对象转换为数组?
- oracle - 从游标中获取行数据 - PL/SQL
- angular - routerLink 和同一个 ion-item 中的单独功能
- firebase - 用于获取上传到 Firebase 托管的文件列表的 API
- django - DRF、modelSerializer相关的嵌套表
- javascript - 为什么打字稿没有给我它应该的类型不匹配错误(根据我的理解)
- angular - Angular node_modules/@types 错误同时(服务构建问题)
- java - 计算多功能算法的最坏情况渐近运行时间