dependency-injection - 尝试进行依赖注入时找不到自定义插件块的类
问题描述
我正在尝试在 Drupal 中创建一个自定义插件块。尝试实际访问我已注册的服务时,我继续收到以下异常:
NOTICE: PHP message: Error: Class 'Drupal\MyNamespace\MyRegisteredService' not found in /var/www/html/web/core/lib/Drupal/Component/DependencyInjection/Container.php on line 259 #0 /var/www/html/web/core/lib/Drupal/Component/DependencyInjection/Container.php(173): Drupal\Component\DependencyInjection\Container->createService(Array, 'foo....')
我已经正确注册了服务,并且正确设置了依赖注入(我相信)它只是访问了不起作用的服务。
我的文件结构目前看起来像:
- web
- modules
- custom
- foo
- foo.services.yml
- src
- MyService.php
- Plugin
- Block
- FooBlock.php
foo.services.yml 看起来像:
services:
foo.my_service:
class: Drupal\MyNamespace\MyRegisteredService
autowire: true
FooBlock.php 看起来像(仅用于依赖注入):
namespace Drupal\foo\Plugin\Block;
use Drupal\MyNamespace\MyRegisteredService
use Drupal\Console\Bootstrap\Drupal;
use Drupal\Core\Block\BlockBase;
use GuzzleHttp\Client;
use Http\Client\Exception;
use phpDocumentor\Reflection\Types\Array_;
use stdClass;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FooBlock extends BlockBase implements ContainerFactoryPluginInterface {
private $my_service;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('foo.my_service'),
);
}
function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
Drupal\MyNamespace\MyRegisteredService $my_registered_service,
) {
$this->my_registered_service = $my_registered_service;
}
MyService.php 看起来像:
<?php
namespace Drupal\MyNamespace;
class MyService
{
static function say_hello()
{
return 'hello world';
}
}
我不确定我尝试设置的方式是否不正确,或者我是否没有正确设置依赖注入。我尝试过但没有成功的一些事情是更改命名空间并Drupal\
从中删除,但这变化不大。
我还尝试了几个关于如何设置服务的指南(例如this ),但运气不佳。
任何帮助,将不胜感激。
解决方案
我不确定您的服务或命名空间路径的实际名称,但我可以在您的占位符引用中看到一些不一致的地方:
请更改所有对
Drupal\MyNamespace\MyRegisteredService
whereDrupal\foo\MyRegisteredService
是foo
模块名称的引用。这应该是小写的。其次
Drupal\MyNamespace\MyRegisteredService
引用一个类名MyRegisteredService
,而您给出的示例类名是MyService
. 这些应该是相等的,所以要么选择一个,要么选择另一个。
推荐阅读
- jsf - 在数据表行扩展中输入文本,返回空值 primefaces
- c# - 如何在 AssetDatabase.FindAssets() 中使用正则表达式?
- flutter - 触摸时将小部件放在前面
- swift - 如何更改静态变量的值?
- blazor - 如何使 Blazor 项目在子文件夹中工作?
- flutter - 颤振中的SignalR出现错误无协议
- twincat - 如何在 PLC 上启用 TcRTime 看门狗?
- mongodb - 无法将多个文档推送到集合 (11000)
- arrays - 转换列表
- > 到 Flutter 中的 ArrayList
- autodesk-forge - Autodesk Forge 转换错误 - 提取器代码 1073741819