我有一个小框架,我像这样编码它。我不确定它是否称为依赖注入。我不知道它是否像一种设计模式。我也不知道并想知道$this
作为参数传递是否是一种不好的做法。
看看这个;(不是一个工作示例,只是将这些代码写入浏览器以进行解释。)
/* This is engine model */
require_once('Database.class.php');
require_once('Image.class.php');
require_once('Misc.class.php');
require_once('BBCode.class.php');
class FrameWork_Engine_Model
{
public $database, $config, $misc, $bbcode, $controller, $image;
function __construct($config)
{
$this->database = new Database($configParams);
$this->image = new Image($this);
$this->misc = new Misc($this);
$this->bbcode = new BBCode($this);
$this->controller = new Controller($this); //here I call Register controller depending on routing, in this case, register controller.
}
...
}
/* This is register controller */
class Register extends Base_Controller
{
/*I can access anything over Engine Model in my controllers */
$this->engine->database->query(); //I access database model
$this->engine->bbcode->tag('you'); //I access bbcode model
$this->engine->image->sanitizeUploadedFile(); //I access image model
//etc. I can access others models like this.
}
基本上,我的控制器可以通过引擎模型访问任何模型。我相信dependency injection is all about injecting dependencies into controllers?
就像,我的注册控制器需要一个数据库模型、路由模型和模板模型才能工作。这里有它所依赖的一切。我弄错了吗?
说了这么多,我的问题是:
它是一个有效的依赖注入示例吗?如果不是,那是什么?它在设计模式中有名字吗?
如果和依赖注入无关,需要做哪些改变才能成为DI?
在新创建的类上传递
$this
参数是一种不好的做法吗?如果是这样,为什么?
附言。我知道在一个主题中问 3 个问题不是 stackoverflow 喜欢的,但我不想复制粘贴整个文本来问他们。