18.01.2021
Создаем собственные обработчики для сущностей Друпал8. Они потребуются для логической структуры приложения, Как бы для единой "точки входа".
Первым делом создадим наш Handler
<?php
namespace Drupal\example\Handler;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Messenger\Messenger;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ArticleHandler implements EntityHandlerInterface{
/**
* The current entity type.
*
* @var EntityTypeInterface
*/
protected $entity_type;
/**
* The messenger service.
*
* @var \Drupal\Core\Messenger\Messenger
*/
protected $messenger;
public function __construct(EntityTypeInterface $entity_type, Messenger $messenger) {
$this->entity_type = $entity_type;
$this->messenger = $messenger;
}
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('messenger')
);
}
}
Используя hook_entity_type_buildподключимнаш handlerк нашей сущности
/**
* Implements hook_entity_type_build().
*
* @param \Drupal\Core\Entity\ContentEntityType[] $entity_types
*/
function example_entity_type_build(array &$entity_types) {
if (isset($entity_types['node'])) {
if (!$entity_types['node']->hasHandlerClass('article_handler')) {
$entity_types['node']->setHandlerClass('article_handler', \Drupal\example\Handler\ArticleHandler::class);
}
}
}
И вызываем наш хэндлер
\Drupal::entityTypeManager()->getHandler('node','article_handler');