dtoqemais553654797 2012-08-23 11:15
浏览 75
已采纳

这会被认为是php / codeigniter中的依赖注入吗?

Would this be considered dependency injection?

<?php
class BASE_Model extends CI_Model 
{  
    /**
     * inject_class - load class using dependency injection
     *
     * @access public
     * @param  string $path
     * @param  string $class
     * @param  string $func
     * @param  string $method
     **/
    public function inject_class($path, $class, $func, $method)
    {
        // load_class is a function located in system/core/common.php on line 123
        $obj = load_class($class, $path, NULL);
        return $obj->$func();
    }
}

// lets say this is instantiated by a user controller when a new user is made
class User_model extends BASE_Model
{
    public function create()
    {
        echo 'create a new user';
        $request = $this->inject_class('path/to/models', 'Logger_model', 'log');
        echo $request;
    }
}

class Logger_model extends BASE_Model
{
    public function log()
    {
        return 'Logged';
    }
}
  • 写回答

1条回答 默认 最新

  • doudu7626 2012-08-23 11:21
    关注

    No. That's just another way of how the object loads dependencies itself. The point of dependency injection is that every method/object/function takes its dependencies as arguments and does not load them itself in any way. User_model::create is injecting loading another class by itself, which is not accepting the dependency as an argument.

    The point of dependency injection is to reduce coupling. The User_model is now coupled to the Logger_model class, since it hardcodes the name and path to that specific class inside itself. If you wanted to use or test the User_model by itself in isolation, without it logging stuff you don't want, you cannot do so anymore. Real DI would be this:

    public function create(Logger_model $log) {
        // here be dragons
        $log->log();
    }
    

    This way you can inject a mocked dummy logging class when you want to test the method without breaking anything or use alternative types of loggers when needed without needing to change any code.

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?