douqin7086 2012-01-12 15:05
浏览 39
已采纳

PHP中的依赖注入困惑(类的链)

I'm moving from Globals and Singletons (=bad?) to Dependency Injections (=good?) in PHP and I'm very new to it.

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);

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); 

Isn't it too much already?

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.

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?
  }
}

That "$this->model->user->id" seems like overkill to me.

  • 写回答

3条回答 默认 最新

  • doulu4976 2012-01-12 15:16
    关注

    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.

    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:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿