【问题标题】:Using PHP-DI for Wordpress Plugin using PSR-4?将 PHP-DI 用于使用 PSR-4 的 Wordpress 插件?
【发布时间】:2018-03-16 15:58:22
【问题描述】:

我正在使用 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 系统的任何建议,我将不胜感激。

【问题讨论】:

    标签: wordpress php-di


    【解决方案1】:

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

    您需要将您的加载程序放在 PHP-DI 配置中的 BHAA\utils\Loader 键下,而不仅仅是 loader(PHP-DI 不会仅使用 loader 神奇地猜测事情)。

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

    【讨论】:

      猜你喜欢
      • 2017-12-10
      • 2019-03-09
      • 2014-09-12
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      相关资源
      最近更新 更多