在Drupal 8中,您可以使用以下方式加载实体:
$node = \Drupal::entityManager()->getStorage('node')->load(123);
这将查找实体定义,并发现该节点是由Drupal \ node \ Entity \ Node定义的-因此(我猜)Drupal \ node \ NodeStorage将实例化一个新的Drupal \ node \ Entity \ Node实例。
我想要实现的是子类化Drupal \ node \ Entity \ Node并能够在适当的时候实例化此子类。例如,如果我有一个节点束文章,那么会有一个类:
namespace Drupal\my_module\Entity\Article;
class Article extends Drupal\node\Entity\Node {
}
我会打电话给:
$node = \Drupal::entityManager()->getStorage('node_article')->load(123);
回报将是我的Article
子类。
我可以通过创建一个新的实体类型并将其连接回另一个现有的实体定义来实现这一点,例如node-article示例就是此类:
namespace Drupal\my_module\Entity;
use Drupal\node\Entity\Node;
/**
* @ContentEntityType(
* id = "node_article",
* label = @Translation("Content"),
* bundle_label = @Translation("Content type"),
* handlers = {
* "storage" = "Drupal\node\NodeStorage",
* "storage_schema" = "Drupal\node\NodeStorageSchema",
* "view_builder" = "Drupal\node\NodeViewBuilder",
* "access" = "Drupal\node\NodeAccessControlHandler",
* "views_data" = "Drupal\node\NodeViewsData",
* "form" = {
* "default" = "Drupal\node\NodeForm",
* "delete" = "Drupal\node\Form\NodeDeleteForm",
* "edit" = "Drupal\node\NodeForm"
* },
* "route_provider" = {
* "html" = "Drupal\node\Entity\NodeRouteProvider",
* },
* "list_builder" = "Drupal\node\NodeListBuilder",
* "translation" = "Drupal\node\NodeTranslationHandler"
* },
* base_table = "node",
* data_table = "node_field_data",
* revision_table = "node_revision",
* revision_data_table = "node_field_revision",
* translatable = TRUE,
* list_cache_contexts = { "user.node_grants:view" },
* entity_keys = {
* "id" = "nid",
* "revision" = "vid",
* "bundle" = "type",
* "label" = "title",
* "langcode" = "langcode",
* "uuid" = "uuid",
* "status" = "status",
* "uid" = "uid",
* },
* bundle_entity_type = "node_type",
* field_ui_base_route = "entity.node_type.edit_form",
* common_reference_target = TRUE,
* permission_granularity = "bundle",
* links = {
* "canonical" = "/node/{node}",
* "delete-form" = "/node/{node}/delete",
* "edit-form" = "/node/{node}/edit",
* "version-history" = "/node/{node}/revisions",
* "revision" = "/node/{node}/revisions/{node_revision}/view",
* }
* )
*/
class Article extends Node { }
// Results my Article sub type.
$node = \Drupal::entityManager()->getStorage('node_article')->load(123);
这很好(据我所知);但是,闻起来。它添加了一个新的实体类型,这是不正确的,将来可能会引起其他麻烦。
如何为实体捆绑包定义子类,以便加载实体将返回该类的对象?
hook_entity_type_alter()
做出改变更干净,但我不知道你会如何限制到特定的捆绑