「已注销」 2012-11-17 20:26 采纳率: 0%
浏览 69
已采纳

依赖性和实例化

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 2012-11-17 21:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题