doudou_0624
「已注销」
2012-11-17 20:26

依赖性和实例化

已采纳

I'm in the middle of trying to move components of my website into classes. This snippet below for example needs to be used in multiple files, but I don't want to copy and paste the code around.

<?php
...
require "ActionManager.php";
require "Action.php";
require "includes/pdo.php";

$actionMan = new ActionManager();
$actionMan->setPDO($pdo);
$actionMan->setUserData($data);
echo $actionMan->getActions(3);
?>

Okay I know I could use spl_autoload_register() to get rid of the first two requires, but I think what I'm looking for is some kind of dependency container, so that I don't end up repeating this code, and screwing myself over when it changes.

Also I find myself repeating the setPDO() and setUserData() methods in a LOT of classess.

Could someone kindly point me in the right direction?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douhuangzhi0707 douhuangzhi0707 9年前

    The require statements should not be there, instead autoload your dependencies. There is a good blog post about the costs and benefits of autoloading by Anthony Ferrara where he concludes that overall, autoloading is the best solution.

    The rest of your code looks a bit like bootstrap code to me. You create one new instance of an ActionManager and inject two dependencies via setter method. If this is indeed bootstrap code at the top level of your dependency hierarchy it is ok to use new. What I don't like is the fact that obviously your dependencies are created in the required files without you being able to say whether or not you need those instances already (no option for lazy instantiation).

    Depending on your application as a whole, you may want to look into using a DIC but I don't like them too much. You can do proper constructor injection without a DIC. Actually, most often people end up using the DIC wrongly and re-create the problems DI is supposed to counter.

    If you were to show us more of your architecture, we might be able to give more concrete advise on how to handle the common dependencies.

    点赞 评论 复制链接分享

相关推荐