Drupal 8 Entity API

Drupal Entity API

D8 Entity可以通过Entity Validation API对多种方式(Form、REST)保存的Entity进行验证。

Entity是含有预定义方法的类

方法类型 方法示例
一般方法 $entity->id()
特定entity的特定方法 $node->getTitle()

注: 通常这些方法定义在interfaces中,目前还没有比较完备的D8 Traits文档
Classes, traits, and interfaces

处理器/调用 Handlers

entity处理器实际上是预定义了对entity进行处理的方法的类。

存储处理器 Storage handler – 支持载入、保存和删除entity等操作,包括对entity多次修订版本、多语言翻译版本和配置字段。

另外,除了存储处理器,还有其他的处理器例如许可控制处理器AccessControlHandler、视图处理器Viewing,列表处理器Listings,表单处理器Forms。

Entity的两种类型

  • Configuration Entity (由D8的Configuration系统使用,可以在安装时配置默认选项,注意Configuration Entity以文件的形式存在,而非存储在数据库表中,例如D8很多的模块下都有config目录,而该目录下的yml文件,一般都是Configuration Entity的配置文件。)
  • Content Entity (包含可配置的基础字段,并且可以根据需要添加其他额外字段,支持多版本和多语言。)

Entity类型

规范

模块的Entity的命名规范
例如:Transport模块定义了名称为Car的entity


/* Transport Car * Defines the Car entity class * * @ContentEntityType( * id = "transport_car", * label = @Translation("Transport Car"), * bundle_label = @Translation("Transport"), * handlers = { * "storage" = "Drupal\transport\CarStorage", * "storage_schema" = "Drupal\transport\CarStorageSchema", * "view_builder" = "Drupal\transport\CarViewBuilder", * "access" = "Drupal\transport\CarAccessControlHandler", * "views_data" = "Drupal\transport\CarViewsData", * "form" = { * "default" = "Drupal\transport\CarForm", * "delete" = "Drupal\transport\Form\CarDeleteForm", * }, * "route_provider" = { * "html" = "Drupal\transport\Entity\CarRouteProvider", * }, * "translation" = "Drupal\transport_car\CarTranslationHandler" * }, * base_table = "transport_car_data", * data_table = "transport_car_field_data", * translatable = TRUE, * list_cache_contexts = { "user.transport_car_grants:view" }, * entity_keys = { * "id" = "cid", * "bundle" = "transport type", * "label" = "title", * "langcode" = "langcode", * "uuid" = "uuid", * }, * field_ui_base_route = "entity.transport_car.edit_form", * common_reference_target = TRUE, * permission_granularity = "bundle", * links = { * "canonical" = "/transport/car/{transport_car}", * "delete-form" = "/transport/car/{transport_car}/delete", * "edit-form" = "/transport/car/{transport_car}/edit", * } * ) * * * transport/src/Entity/Car.php * Car Entity类定义文件 * */ namespace Drupal\trasnsport\Entity class Car extend ContentEntityBase { use EntityChangedTrait; public function carFunction1 () { //do something }; } # 位于modules/custom/transport/src/Entity/目录下