依赖注入简单实现 [英] Dependency Injection simple implementation

查看:57
本文介绍了依赖注入简单实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读这个的问题,我想知道有人可以帮助我了解如何使用这些PHP类正确实现依赖注入:

after reading this question i wonder if someone can help me understand how to implement correctly Dependency Injection with these PHP Classes:

class DBClass
{
    private $mMysqli;
    function  __construct(mysqli $database)
    {
        $this->mMysqli=$database;
    }
    function __destruct()
    {
        $this->mMysqli->close();
    }

    public function listUsers()
    {
        $query='SELECT * FROM Utente;';
        $resultset=$this->mMysqli->query($query);
        while($row = $resultset->fetch_array(MYSQLI_ASSOC)) {
            echo $row['username'];
            echo $row['pwd'];
            echo "<br />\n";
        }

    }

    public function runQuery($query)
    {
        return $resultset=$this->mMysqli->query($query);
    }

    public function getConnection()
    {
        return $this->mMysqli;
    }
}

会话类:

class Session
{
    private $_session;
    public $maxTime;
    private $database;

    public function __construct(DBClass $database)
    {
        $this->database=$database;
        $this->maxTime['access'] = time();
        $this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');
        session_set_save_handler(array($this,'_open'),
                array($this,'_close'),
                array($this,'_read'),
                array($this,'_write'),
                array($this,'_destroy'),
                array($this,'_clean')
                );
        register_shutdown_function('session_write_close');
        session_start();
        ...
     }
}   

用户类有关当前登录用户的详细信息):

User Class (for details about the currently logged in user):

class User
{
    private $username;
    private $role;
    private $session;

    function __construct($session)
    {
        $this->session=$session;
        ...
    }
}

外部: p>

Externally:

$connection=new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
$database=new DBClass($connection);
$session=new Session($database);
$user=new User($session);

这是正确的方法吗?

推荐答案

是的。您正在通过构造函数注入依赖关系,该构造函数提供较少的耦合。现在,您可以更轻松地交换这些依赖关系,例如当您使用单元测试,您可以用Mocks替换它们。

Yes. You are now injecting the dependencies through the constructor which provides for less coupling. You can now more easily swap out these dependencies, e.g. when UnitTesting you can replace them with Mocks.

您仍然有一些耦合,尽管通过使用具体的DBClass作为TypeHint而不是界面。所以当你想使用不同的DBClass时,它必须被命名为DBClass。您可以通过针对界面编码来实现更多松散耦合,具体类必须

You have still some coupling though by using the concrete DBClass as a TypeHint instead of an interface. So when you would want to use a different DBClass, it would have to be named DBClass. You could achieve more loose coupling by coding against an interface that the concrete classes have to implement instead.

要仅创建一个类的单个实例(如评论中所述),您可以使用Singleton(如Kevin Peno建议)或Factory创建并跟踪实例是否已创建。或者使用与工厂相似的DI服务容器,但不一样。它为您创建和管理对象。

To create only single instances of a class (as asked in the comments), you could either use a Singleton (like Kevin Peno suggested) or a Factory to create and keep track of if the instance has been created yet. Or use a DI Service Container, which is similar to a Factory, yet not the same thing. It creates and manages objects for you.

Symfony组件库具有依赖注入容器,具有出色的文档,并介绍了有关如何使用服务容器进一步增强DI的主题。容器也可以用来限制实例。检查出来。

The Symfony Components library has a Dependency Injection Container with excellent documentation and introduction to the topic on how to further enhance DI this with Service Containers. The containers can also be used to limit instances. Check it out.

这篇关于依赖注入简单实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆