2

我正在使用https://github.com/DevinVinson/WordPress-Plugin-Boilerplate模板编写一个 wordpress 插件,并且我正在尝试配置 PHP-DI ( http://php-di.org/ ) 来处理注入我的插件中的类。

我的作曲家配置是这样的

{
  "name" : "emeraldjava/bhaa_wordpress_plugin",
  "description" : "bhaa_wordpress_plugin",
  "type" : "wordpress-plugin",
  "require": {
    "php-di/php-di": "^6.0"
  },
  "autoload" : {
    "psr-4" : {
      "BHAA\\" : "src"
    }
  }
} 

在我的 Main.php 类中,我正在创建 PHP-DI Container 对象,并且我希望自动装配应该生效,所以我不需要在 addDefinitions() 方法中注册很多对象。

use DI\ContainerBuilder;

use function DI\autowire;
use function DI\create;

class Main {

    public function __construct() {
        // This is the current manual initialisation of the Loader class. I want to be able to inject this object reference
        $this->loader = new utils\Loader();
        $this->buildContainer();
    }

    private function buildContainer() {
        $builder = new ContainerBuilder();
        $builder->addDefinitions([
            // I add the object definition to the container here
            'loader' => $this->loader,
        ]);
        $this->container = $builder->build();
    }    
}

我有一个名为 LeagueCPT 的新类,我想在其中注入 Loader 对象引用

namespace BHAA\front\cpt;

use BHAA\utils\Loader;

class LeagueCPT {

    private $loader;

    public function __construct(Loader $loader) {
        // i'm expecting that Loader will be injected here but it's null
    }
}

在原始代码中,我会手动创建 LeagueCPT 并手动传递引用,就像这样

class Main {

    public function __construct() {
        $this->leagueCpt = new front\cpt\LeagueCPT($this->loader);
    }
}

我现在期待我应该能够调用 Container 来为 League 创建一个新对象,并注入正确的构造函数

class Main {

    public function __construct() {
        $this->leagueCpt = $this->getContainer()->get(LeagueCPT);
    }
}

但在每种情况下,我都看不到 LeagueCPT 被 PHP-DI 初始化。对于在这种情况下如何正确配置 DI 系统的任何建议,我将不胜感激。

4

1 回答 1

2

自动装配通过检查参数的类型提示来工作。在您的构造函数中,您有Loader $loader.

你需要把你的加载器放在 PHP-DI 配置中的BHAA\utils\Loaderkey 下,而不仅仅是loader(PHP-DI 不会用 just 神奇地猜测事情loader)。

所以替换'loader' => $this->loader,\BHAA\utils\Loader::class => $this->loader,,你应该很好。

于 2018-03-18T20:05:58.893 回答