覆盖 FieldPluginBase 初始化函数 Drupal

override FieldPluginBase init function Drupal

是否可以将自定义服务注入扩展 FieldPluginBase 的 class?

  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->currentDisplay = $view->current_display;
  }

当我尝试注入我的一项服务时,出现错误:

Fatal error: Declaration of Drupal\xxx_api\Plugin\views\field\NewsViewsField::init(Drupal\views\ViewExecutable $view, Drupal\views\Plugin\views\display\DisplayPluginBase $display, ?array &$options, Drupal\xxx_api\Service\ArticleService $articleService) must be compatible with Drupal\views\Plugin\views\field\FieldPluginBase::init(Drupal\views\ViewExecutable $view, Drupal\views\Plugin\views\display\DisplayPluginBase $display, ?array &$options = NULL)

预先感谢您的帮助:)

是的,这是可能的,但您应该在构造函数中或通过 create() 方法注入它。

在您要从中扩展 FieldPluginBase class 的同一个 views 核心模块中,有一个 RenderedEntity class 这是一个很好的例子这样做。

因此,在您的情况下,这可能类似于下面的内容。请注意,我使用 YourService 作为您尝试注入的服务的占位符:

namespace Drupal\xxx_api\Plugin\views\field;

/**
 * Example Views field.
 *
 * @ViewsField("news_views_field")
 */
class NewsViewsField extends FieldPluginBase {

  /**
   * Your Service interface.
   *
   * @var \Drupal\foo\YourServiceInterface
   */
  protected $yourService;

  /**
   * Constructs a NewsViewsField object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\foo\YourServiceInterface $your_service
   *   Your Service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, YourServiceInterface $your_service) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    // Inject your service.
    $this->yourService = $your_service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      // Add your service here to pass an instance to the constructor.
      $container->get('your.service')
    );
  }

  ...

}