Entity Type Class

Categories

Component ID

2899742

Component name

Entity Type Class

Component type

module

Maintenance status

Development status

Component security advisory coverage

not-covered

Downloads

267

Component created

Component changed

Component body

This module is now part of the Developer Suite project and will be minimally maintained (bug fixes only).

Provides a plugin based system to alter entity type classes. It currently support overriding Node, User and File entity type classes.

Introduction

Typically you would want to extend entity type classes to create your own getters and setters or to override/extend the entity parents methods. By creating custom getters and setters on Drupal fields (such as `title`) you are able to provide doc blocks which in turn can help during development.

While powerful, overriding entity type classes is an advanced undertaking and potentially can break your site hard and fast. I would strongly recommend using this module only if you fully understand what you are doing.

Example (overriding the Node type class)

1. Create a new Node class (for example ArticleNode) and extend the Drupal odeEntityNode class.

2. Create a new EntityTypeClass plugin in Drupalmy_modulePluginEntityTypeClass and extend the Drupalentity_type_classStorageNodeStorage class (the other options for now are the UserStorage and FileStorage classes).

3. Decorate the class with the @EntityTypeClass annotation and provide the id, entity and label. The entity should be the system name of the Entity, in this case 'node'. In your custom plugin you are required to implement the getEntityTypeClass() method. This method should return the fully qualified class name of your custom Entity class.

<?php

namespace Drupalmy_modulePluginEntityTypeClass;

use Drupalentity_type_classStorageNodeStorage;
use Drupal
odeEntityNode;
use Drupalmy_moduleEntityArticleNode;
use Drupalmy_moduleEntityPageNode;

/**
 * Class NodeTypeStorage.
 *
 * @EntityTypeClass(
 *   id = "node_type_class",
 *   entity = "node",
 *   label = @Translation("Node type class"),
 * )
 */
class NodeTypeClass extends NodeStorage {

  /**
   * Returns the entity class by type.
   *
   * @param string $type
   *   The entity type.
   *
   * @return string
   *   The entity class.
   */
  public function getEntityTypeClass($type) {
    switch ($type) {
      case 'article':
        return ArticleNode::class;

      case 'page':
        return PageNode::class;
    }

    return Node::class;
  }

}