【问题标题】:Accessing Dependencies with a Foreach Loop使用 Foreach 循环访问依赖项
【发布时间】:2016-12-09 11:45:41
【问题描述】:

我正在尝试制作一个简单的依赖“映射器”,我认为我什至不能称它为依赖注入器......所以我试图在下面做一个最小的概念证明。

在我的 index.php 页面上,我有以下内容...

// >>> psr-4 autoloader here

// instantiating the container
$container = new Container;

// getting an instance of 'A' with an object tree of A->B->C
$a = $container->get('A');

在我的简单容器中,我有这个...

class Container
{
    public $dependencies = []; // an array of dependencies from the dependency file

    public function __construct()
    {
        // include list of dependencies
        include 'Dependencies.php';

        foreach ($dependency as $key => $value) {
            $this->dependencies[$key] = $value; // e.g. dependency['A'] = ['B'];
        }
    }

    /**
     * gets the dependency to instantiate
     */
    public function get($string)
    {

        if (isset($this->dependencies[$string])) {

            $a = $string;

            foreach ($this->dependencies[$string] as $dependency) {

                $b = $dependency;

                if (isset($this->dependencies[$dependency])) {

                    foreach ($this->dependencies[$dependency] as $dependency);

                    $c = $dependency;

                }

            }

        }

        $instance = new $a(new $b(new $c));
        return $instance;

    }
}

我将我的依赖项映射到一个单独的文件中,如下所示...

/**
 * to add a dependency, write the full namespace
 */

$dependency['A'] = [
    'B' // A depends on B
];

$dependency['B'] = [
    'C' // which depends on C
];

还有一组相互依赖的类A、B和C......

class A
{
    public function __construct(B $b)
    {
        echo 'Hello, I am A! <br>';
    }
}



class B
{
    public function __construct(C $c)
    {
        echo 'Hello, I am B!<br>';
    }
}



class C
{
    public function __construct()
    {
        echo 'Hello, I am C! <br>';
    }
}

我整个下午都在努力工作,但我担心要么我想得不够清楚

问题

那么在我的get() 函数中,我怎样才能使这些依赖项的加载自动进行,以便我的 get 函数不仅仅是 foreachifelse 的永无止境的嵌套strong> 语句...我需要添加某种回调吗?我真的不清楚,我必须强调,我已经尝试了很多不同的方法,但没有奏效,太多了,无法包括。

【问题讨论】:

  • 你为什么要使用设置类结构并将它们保存在某处而不是自动装配(建议here)。使用反射类自动装配允许 PHP 自动检测依赖关系,而不是从数组/文件中读取它们。

标签: php arrays oop multidimensional-array dependency-injection


【解决方案1】:

你做错了。您的容器设计为仅使用该依赖结构。例如,$container-&gt;get('B') 将不起作用,$container-&gt;get('C') 也不起作用,因为 $c 将为 null 并且第三个嵌套的 new 将失败。

我建议您将容器设置为 recursive 函数。

顺便说一句,第三个foreach 是怎么回事?您是否正在尝试获取最后一个依赖项?

你可以阅读我的article

【讨论】:

猜你喜欢
  • 2020-11-18
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
相关资源
最近更新 更多