困惑于PHP中的依赖注入(类链) [英] Puzzled with Dependency Injection in PHP (chains of Classes)
问题描述
我正在从PHP中的Globals和Singletons(= bad?)转向Dependency Injections(= good?),我对此很陌生.
I'm moving from Globals and Singletons (=bad?) to Dependency Injections (=good?) in PHP and I'm very new to it.
我已经阅读了许多有关Stack Overflow的相关主题,但是我仍然不了解DI的主要原理.
I have read many related topics on Stack Overflow already but I still can't understand the main principles of DI.
请告诉我我是否做对了(只是缩短了伪代码):
Please tell me if I'm doing it right (it's just shortened pseudo-code):
// first connect to DB
$sql = new Sql();
// create logger (I'm writing logs to Database so I need to pass $sql to it)
$log = new Log($sql);
// restore logged in user, get info about user, unread messages...
// class "User" needs access to Database and Logs:
$user = new User($sql, $log);
// now we need to collect all the data of current section of my Website
// I'm using Model and Controller:
$model = new FrontPageModel($sql, $user, $log);
$pageController = new FrontPageController($model);
尽管在此步骤中看起来不错,但是如果我需要访问更多类(例如Config,Session等)怎么办?
Though it may look OK at this step but what if I need to get access to more classes like Config, Session, etc.?
我的代码应该转换成这个吗?
Should my code transform to this?
$model = new FrontPageModel($sql, $user, $log, $config, $session);
不是很多吗?
我知道有人会建议使用一种大的"Application"类,并将Config,Session,Log,Db对象放在该类中,但是我觉得这不是一个好主意.
I know someone could advice to use a kind of big "Application" class and put Config, Session, Log, Db objects inside of this class but I feel that it isn't very good idea.
下一个问题-如果我需要在FrontPageController中获取已记录的用户ID怎么办?我没有将用户"的实例传递给FrontPageController,但它是在链中传递给FronPageModel的.
Next question - what if I need to get logged User's ID inside of my FrontPageController? I did not pass an instance of "User" to FrontPageController, but it was passed before (in chain) to FronPageModel.
class FrontPageController{
private $model;
function __construct($model){
$this->model = $model;
}
function getData(){
echo $this->model->user->id; // is it right way?
}
}
"$ this-> model-> user-> id"对我来说似乎太过分了.
That "$this->model->user->id" seems like overkill to me.
推荐答案
它可能不是最漂亮的,但是您肯定不是在错误"地做它.您正在演示分类构造函数注入,但是您也许可以重构,以使一些不同的对象分开更多.
It might not be the prettiest, but you're certainly not doing it "wrong". You're demonstrating classing constructor injection, but you could perhaps refactor to keep some of the disparate objects separated a bit more.
我的建议是查看已建立的PHP DI容器.看看它们是如何工作的,并在一些应用程序中使用它们,以及(1)您将拥有更多可测试的应用程序,以及(2)一般来说,您对DI的使用会更加舒适.
My suggestion would be to look at established PHP DI containers. See how they work, use them in a few apps, and (1) you'll have much more testable apps and (2) you'll be much more comfortable with DI in general.
看看以下一项或多项内容:
Take a look at one or more of the following:
- Pimple
- Aura DI
- Symfony DI
这篇关于困惑于PHP中的依赖注入(类链)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!