创建实体类型

admin 提交于 周三, 06/07/2023 - 15:21
创建实体类型

用插件的方式定义 Entity bundle

Drupal 核心提供的内容实体 bundle 机制是通过 配置实体 来实现的,这意味着无法通过 php 代码来创建实体。

在 Drupal 7 的时代,Entity API 是一个社区模块,并不包含在核心,Drupal 8 的时候才并进核心。 去看 Entity模块的主页,会发现上面依然有 8.x 的版本, 这个Entity模块的 drupal8版本 和 Drupal8核心 的 Entity API 并不是重复的, 一是些没有被采纳进核心的EntityAPI特性,有一些人觉得很有用,所以放在这里,方便开发时使用。 这些特性经过社区验证之后,有一天也许也会并进Drupal8核心。

通过编写插件的方式来创建 Entity Bundle,是这社区 Entity 模块的一个重要特性。

在 @ContentEntity 注解代码中通过 bundle_plugin_type 的属性来指定要使用的插件类型, 它的值是一个插件类型ID,这意味着 EntityAPI 会为每一个该类型的插件创建一个对应的Entity Bundle。 所有该用途的插件,都应该实现 Drupal\entity\BundlePlugin\BundlePluginInterface 接口:

<?php

namespace Drupal\entity\BundlePlugin;

use Drupal\Component\Plugin\PluginInspectionInterface;

/**
 * Interface for plugins which act as entity bundles.
 */
interface BundlePluginInterface extends PluginInspectionInterface {

  /**
   * Builds the field definitions for entities of this bundle.
   *
   * Important:
   * Field names must be unique across all bundles.
   * It is recommended to prefix them with the bundle name (plugin ID).
   *
   * @return \Drupal\entity\BundleFieldDefinition[]
   *   An array of bundle field definitions, keyed by field name.
   */
  public function buildFieldDefinitions();

}

该接口定义了一个 buildFieldDefinitions() 方法,该方法用于返回要创建的 Bundle 的自有字段定义。 这里的字段定义应该使用 Drupal\entity\BundleFieldDefinition::create() 方法来创建。

Commerce core 模块中,commerce_paymentcommerce_payment_method 两个内容实体, 它们就是通过插件的方法来创建 bundle 的,它的代码有很大的参考价值。