会在php / codeigniter中将其视为依赖项注入吗?

And*_*lin 0 php oop design-patterns codeigniter

这将被视为依赖注入吗?

<?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';
    }
}
Run Code Online (Sandbox Code Playgroud)

dec*_*eze 6

否。这只是对象如何加载依赖项本身的另一种方式。依赖项注入的要点是,每个方法/对象/函数都将其依赖项作为参数,并且不会以任何方式本身加载它们。User_model::create正在注入自己加载另一个类,该类不接受依赖项作为参数

依赖项注入的目的是减少耦合。在User_model现在连接到Logger_model的类,因为它的硬编码名称和路径里面本身特定的类。如果您想单独使用或测试User_model,而没有记录您不需要的内容,您将无法再这样做。真正的DI将是这样的:

public function create(Logger_model $log) {
    // here be dragons
    $log->log();
}
Run Code Online (Sandbox Code Playgroud)

这样,当您想测试该方法而不会破坏任何内容时,可以注入模拟的虚拟日志记录类,或者在需要时使用其他类型的记录器,而无需更改任何代码。