我如何使用“依赖注入"?在简单的 php 函数中,我应该打扰吗?

How can I use quot;Dependency Injectionquot; in simple php functions, and should I bother?(我如何使用“依赖注入?在简单的 php 函数中,我应该打扰吗?)
本文介绍了我如何使用“依赖注入"?在简单的 php 函数中,我应该打扰吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我一直听到人们谈论依赖注入及其好处,但我并不真正理解.

I hear people talking about dependency injection and the benefit of it all the time, but I don't really understand it.

我想知道这是否是我一直将数据库连接作为参数传递"问题的解决方案.

I'm wondering if it's a solution to the "I pass database connections as arguments all the time" problem.

我尝试阅读维基百科关于它的条目,但该示例是用 Java 编写的,所以我不能完全理解它试图阐明的区别.( http://en.wikipedia.org/wiki/Dependency_injection).

I tried reading wikipedia's entry on it, but the example is written in Java so I don't solidly understand the difference it is trying to make clear. ( http://en.wikipedia.org/wiki/Dependency_injection ).

我阅读了这篇关于 php 依赖注入的文章 ( http://www.potstuck.com/2009/01/08/php-dependency-injection/ ),似乎目标不是直接将依赖项传递给对象,而是封锁创建一个对象以及它的依赖项的创建.不过,我不确定如何在使用 php 函数的上下文中应用它.

I read this dependency-injection-in-php article ( http://www.potstuck.com/2009/01/08/php-dependency-injection/ ), and it seems like the objective is to not pass dependencies to an object directly, but to cordon off the creation of an object along with the creation of it's dependencies. I'm not sure how to apply that in a using php functions context, though.

另外,下面是依赖注入,我是否应该费心尝试在函数上下文中进行依赖注入?

Additionally, is the following Dependency Injection, and should I bother trying to do dependency injection in a functional context?

版本 1:(我每天创建但不喜欢的那种代码)

Version 1: (the kind of code that I create, but don't like, every day)

function get_data_from_database($database_connection){
    $data = $database_connection->query('blah');
    return $data;
}

版本 2:(不必传递数据库连接,但也许不需要依赖注入?)

Version 2: (don't have to pass a database connection, but perhaps not dependency injection?)

function get_database_connection(){
    static $db_connection;
    if($db_connection){
        return $db_connection;
    } else {
        // create db_connection
      ...
    }
}

function get_data_from_database(){
   $conn = get_database_connection();
   $data = $conn->query('blah');
   return $data;
}

$data = get_data_from_database();

版本3:(对象"/数据的创建是分开的,数据库代码是静止的,所以这可能算作依赖注入?)

Version 3: (the creation of the "object"/data is separate, and the database code is still, so perhaps this would count as dependency injection?)

function factory_of_data_set(){
    static $db_connection;
    $data_set = null;
    $db_connection = get_database_connection();
    $data_set = $db_connection->query('blah');
    return $data_set;
}

$data = factory_of_data_set();

有没有人有很好的资源或只是洞察力,使方法和好处 - 晶莹剔透?

Anyone have a good resource or just insight that makes the method and benefit -crystal- clear?

推荐答案

依赖注入是一个大词,表示我的构造函数中有更多参数".

Dependency injection is a big word for "I have some more parameters in my constructor".

当你不喜欢全局变量时,这就是你在可怕的 Singleton 浪潮之前所做的:

It's what you did before the awfull Singleton wave when you did not like globals :

<?php
class User {
    private $_db;
    function __construct($db) {
        $this->_db = $db;
    }
}

$db   = new Db();
$user = new User($db);

现在,诀窍是使用单个类来管理您的依赖项,就像这样:

Now, the trick is to use a single class to manage your dependencies, something like that :

class DependencyContainer 
{
    private _instances = array();
    private _params = array();

    public function __construct($params)
    {
        $this->_params = $params;
    }

    public function getDb()
    {
        if (empty($this->_instances['db']) 
            || !is_a($this->_instances['db'], 'PDO')
        ) {
            $this->_instances['db'] = new PDO(
                $this->_params['dsn'],
                $this->_params['dbUser'], 
                $this->_params['dbPwd']
            );
        }
        return $this->_instances['db'];
    }
}

class User
{
    private $_db;
    public function __construct(DependencyContainer $di)
    {
         $this->_db = $di->getDb();
    }
}

$dependencies = new DependencyContainer($someParams);
$user = new User($dependencies);

你一定认为你只是另一个类和更多的复杂性.但是,您的用户类可能需要像许多其他类一样记录消息.只需将 getMessageHandler 函数添加到您的依赖项容器,并将一些 $this->_messages = $di->getMessageHandler() 添加到您的用户类.其余代码无需更改.

You must think you just another class and more complexity. But, your user class may need something to log messages like lot of other classes. Just add a getMessageHandler function to your dependency container, and some $this->_messages = $di->getMessageHandler() to your user class. Nothing to change in the rest of your code.

你会得到很多关于 symfony 的文档

这篇关于我如何使用“依赖注入"?在简单的 php 函数中,我应该打扰吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)