简体   繁体   English

依赖注入。 这是正确的吗?

[英]Dependency injection. Is this right?

Another question trying to verify the understanding of OOP dependencies of classes. 另一个问题试图验证对类的OOP依赖关系的理解。

Although I knew PHP 4.* quite well, I have only recently restarted programming, and thus started working on OOP so please be gentle ;) 尽管我非常了解PHP 4. *,但我只是最近才重新开始编程,因此才开始在OOP上工作,所以请放心;)

Classes should be as independent as possible I understand. 据我了解,课程应该尽可能独立。 So, when I have a class institute that gets information from a database, I would have to inject institute with an instance of the database class, right?: 因此,当我有一个从数据库获取信息的班级研究所时,我将不得不向研究所注入数据库类的实例,对吗?

$dbh = new database();
$a = new institute();

$a->SetDBI($dbh);

In database, I have a method pulling one record from the database, and is fed with the table table, the ID column and the actual ID of the record to be pulled. 在数据库中,我有一种从数据库中拉出一条记录的方法,并与表表,ID列和要拉出的记录的实际ID一起提供。

Now, say I want one method in Institute that gets one institute. 现在,说我想在研究所获得一种方法的一种方法。 To me it would make sense to then use the database class method getone() : 对我来说,然后使用数据库类方法getone()

public function GetInstitute()
{
    $record = $this->dbi->GetOneRecord('table', 'column', $this->id);
}

Is this the right way of going about it? 这是正确的做法吗? It feel that I am still building dependencies between classes this way? 感觉我仍然以此方式建立类之间的依赖关系吗?

The question is: am I building dependencies that should not be here? 问题是:我是否正在建立不应在此处的依赖项? Or is it standard practice to use methods from one class in another class, as shown in the example? 还是如示例所示,使用来自另一类的方法的标准实践?

This is right. 这是对的。 You still have some dependencies between classes, but only to a certain degree. 类之间仍然有一些依赖关系,但是只有一定程度的依赖。 Actually (because of PHP's weak typing), you can pass any class, and it will work as long as it implements the GetOneRecord method properly. 实际上(由于PHP的弱类型输入),您可以传递任何类,并且只要它正确实现GetOneRecord方法,它就可以工作。

To make it a little more strict, you can use a base class or an interface and add type hinting to the setDBI method, but otherwise, this is the way to go. 为了使其更加严格,可以使用基类或接口,并将类型提示添加到setDBI方法中,但是否则,这是必须采取的方法。

But for the implementation detail, I'm not so sure. 但是对于实现细节,我不太确定。 I see you pass a table name and column name to the database object. 我看到您将表名和列名传递给数据库对象。 That is not right. 那是不对的。 You don't want your Institution to know how and where it is saved. 您不希望您的机构知道如何保存它以及保存在哪里。 I'd rather see that you passed an object implementing a LoadInstitution($id) method. 我宁愿看到您传递了一个实现LoadInstitution($id)方法的对象。 But I find it hard to give you a solid example, because it's unclear to me what GetInstitute is meant to do in the first place. 但是我很难举一个可靠的例子,因为我不清楚GetInstitute首先要做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM