我正在使用https://github.com/DevinVinson/WordPress-Plugin-Boilerplate模板编写一个wordpress插件,并尝试配置PHP-DI (http://php-di.org/)来处理跨插件的类注入。
我的composer配置是这样的
{
"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来为able创建一个新的对象,并注入正确的构造函数
class Main {
public function __construct() {
$this->leagueCpt = $this->getContainer()->get(LeagueCPT);
}
}但在每种情况下,我都看不到LeagueCPT会被PHP-DI初始化。如果有任何关于如何在这种情况下正确配置DI系统的建议,我将不胜感激。
发布于 2018-03-19 04:05:59
自动装配通过检查参数的类型提示来工作。在你的构造函数中,你有Loader $loader。
您需要将您的加载器放在PHP配置中的PHP键下,而不仅仅是loader ( BHAA\utils\Loader -DI不会仅仅使用loader来神奇地猜测)。
所以用\BHAA\utils\Loader::class => $this->loader,替换'loader' => $this->loader,,你应该很好。
https://stackoverflow.com/questions/49324958
复制相似问题