Drupal - Comment surcharger vos nodes avec les classes de bundle

Drupal - Comment surcharger vos nodes avec les classes de bundle

Cela n'est pas franchement une nouveauté, les Classes de Bundle (Bundle Classes) ont été introduites dans le core dès Drupal 9.3 en 2021. Pourtant, je vois encore beaucoup de projets qui s'en passent, et cela fait longtemps que je voulais aborder le sujet ici.

C'est une fonctionnalité qui change la donne en termes d'architecture et de maintenabilité. Aujourd'hui, nous allons voir comment les mettre en place, en profitant de l'occasion pour utiliser la nouvelle syntaxe de hooks orientée objet disponible depuis Drupal 11 (voir à ce sujet : https://kgaut.net/blog/2024/drupal-11-utiliser-la-nouvelle-syntaxe-orientee-objet-pour-les-hooks)

Pourquoi les classes de bundle ?

De tout temps dans Drupal, le contenu est principalement représenté par des nœuds. Techniquement, un nœud de type "Article" et un nœud de type "Concert" sont tous deux des instances de la même classe générique : Drupal\node\Entity\Node.

Depuis Drupal 8, il est possible de surcharger cette classe pour y ajouter une couche métier. Imaginons que vous ayez un type de contenu "Concert" avec un champ date. Vous pourriez vouloir une méthode getDateConcert() pour récupérer cette date formatée facilement.

Le problème, c'est que si vous surchargez la classe Node générique, cette méthode getDateConcert() se retrouve disponible sur tous vos nœuds, y compris les articles de blog ou les pages statiques, ce qui n'a aucun sens sémantiquement.

C'est là qu'interviennent les Classes de Bundle. Elles permettent de corriger ce défaut en définissant une classe PHP spécifique pour un bundle précis.

Exemple d'utilisation : Concerts et Articles

Prenons un exemple concret. Dans un module personnalisé mon_module, nous voulons gérer deux types de contenus :

   Concert (concert) : Nous voulons une méthode pour récupérer facilement sa date.

   Article (article) : Nous voulons juste qu'il ait sa propre classe pour de futurs besoins.

Étape 1 : Créer les classes

Pour faire les choses proprement et avoir un socle solide, je commence par définir une classe abstraite. Elle servira de base à toutes mes classes de bundle de nœuds et contiendra les méthodes communes si besoin.

Fichier : mon_module/src/Entity/AbstractNode.php

<?php

namespace Drupal\mon_module\Entity;

use Drupal\node\Entity\Node;

/**
 * Classe abstraite de base pour nos classes de bundle.
 */
abstract class AbstractNode extends Node {
    // On pourra ajouter ici des méthodes utiles à tous nos types de contenus.
}

Ensuite, je crée la classe spécifique pour mon type de contenu "Concert". C'est ici que j'ajoute ma logique métier.

Fichier : mon_module/src/Entity/ConcertNode.php

<?php

namespace Drupal\mon_module\Entity;

use Drupal\Core\Datetime\DrupalDateTime;

/**
 * Classe spécifique pour le bundle 'concert'.
 */
class ConcertNode extends AbstractNode {

  /**
   * Retourne la date du concert sous forme d'objet DrupalDateTime.
   *
   * @return \Drupal\Core\Datetime\DrupalDateTime|null
   * La date du concert ou null si le champ est vide.
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   */
  public function getDate(): ?DrupalDateTime {
    if ($this->hasField('field_date') && !$this->get('field_date')->isEmpty()) {
        return $this->get('field_date')->date;
    }
    return null;
  }

  /**
   * Une méthode helper pour savoir si le concert est passé.
   */
  public function isPast(): bool {
      $date = $this->getDate();
      if ($date) {
          return $date->getTimestamp() < \Drupal::time()->getRequestTime();
      }
      return FALSE;
  }

}

Je crée aussi rapidement celle pour l'article, même si elle est vide pour l'instant : 

Fichier : mon_module/src/Entity/ArticleNode.php

<?php

namespace Drupal\mon_module\Entity;

class ArticleNode extends AbstractNode {}

 

Étape 2 : Déclarer les classes (Nouvelle méthode Drupal 11)

Maintenant, il faut dire à Drupal : "Quand tu charges un nœud de type 'concert', utilise ma classe ConcertNode au lieu de la classe par défaut".

Cela se fait via le hook entity_bundle_info_alter. Utilisons la syntaxe moderne avec les attributs PHP dans une classe dédiée aux hooks :

Fichier : mon_module/src/Hook/EntityHooks.php

<?php

namespace Drupal\mon_module\Hook;

use Drupal\Core\Hook\Attribute\Hook;
use Drupal\mon_module\Entity\ArticleNode;
use Drupal\mon_module\Entity\ConcertNode;

/**
 * Fournit les implémentations de hooks relatives aux entités.
 */
final class EntityHooks {

  /**
   * Implements hook_entity_bundle_info_alter().
   *
   * Modifie la définition des bundles pour associer nos classes personnalisées.
   */
  #[Hook('entity_bundle_info_alter')]
  public function bundleInfoAlter(array &$bundles): void {
    // Mapping pour le type de contenu 'concert'
    if (isset($bundles['node']['concert'])) {
      $bundles['node']['concert']['class'] = ConcertNode::class;
    }
    // Mapping pour le type de contenu 'article'
    if (isset($bundles['node']['article'])) {
      $bundles['node']['article']['class'] = ArticleNode::class;
    }
  }

}

N'oubliez pas de vider les caches pour que Drupal prenne en compte le nouveau hook et les nouvelles classes !

Le résultat : une utilisation simplifiée

C'est là que la magie opère. Vous n'avez rien à changer dans votre manière de charger des entités. Drupal instanciera automatiquement la bonne classe.

Dans du code PHP (un contrôleur, un service...) :

use Drupal\node\Entity\Node;
use Drupal\mon_module\Entity\ConcertNode;

$nid = 25; // Imaginons que le nœud 25 est un concert.
$entity = Node::load($nid);

// PHP sait maintenant que $entity est une instance de ConcertNode.
if ($entity instanceof ConcertNode) {
    // On peut appeler nos méthodes personnalisées directement.
    $date = $entity->getDate();
    
    if ($entity->isPast()) {
        // Logique spécifique si le concert est passé...
    }
}

Dans Twig

C'est encore plus agréable pour les développeurs front-end. Grâce à la magie des getters dans Twig, getDate() devient accessible via node.date (si le nom ne rentre pas en conflit avec un champ) ou en appelant la méthode directement.

{# Dans node--concert.html.twig #}

<article class="concert {{ node.isPast ? 'concert--past' : 'concert--upcoming' }}">
  <h2>{{ label }}</h2>
  {# Appel direct de la méthode #}
  <p>Date du concert : {{ node.getDate().format('d/m/Y') }}</p>
  
  {# Utilisation de la méthode booléenne #}
  {% if node.isPast() %}
    <span class="badge">Concert terminé</span>
  {% endif %}
</article>

Fini les preprocess compliqués pour calculer des états ou formater des dates spécifiques !

Au-delà des Nœuds

L'exemple ici porte sur les nœuds, mais cela s'applique évidemment à l'ensemble des types d'entités de contenu : Utilisateurs, Termes de taxonomie, Media, etc.

Dans votre hook, vous pourriez ajouter :

// Dans EntityHooks::bundleInfoAlter

// Pour un vocabulaire 'tags'
if (isset($bundles['taxonomy_term']['tags'])) {
  $bundles['taxonomy_term']['tags']['class'] = TagTerm::class;
}
// Pour les utilisateurs (le bundle s'appelle aussi 'user')
if (isset($bundles['user']['user'])) {
  $bundles['user']['user']['class'] = UserCustom::class;
}

Conclusion

À titre personnel, je trouve cette fonctionnalité indispensable sur tout projet Drupal moderne. Cela permet d'ajouter toute une couche métier (getters, setters, méthodes utilitaires) directement là où elle doit être : dans l'objet qui représente la donnée.

Le code devient beaucoup plus propre, orienté objet, plus facile à tester unitairement, et bien plus maintenable sur le long terme. Si vous ne les utilisez pas encore, foncez !

Voir la présentation sur drupal.org : https://www.drupal.org/node/3191609

Contenus en rapport

Drupal 8 - Surcharger la classe de formulaire d'un nœud

Pour modifier le formulaire de création d'un nœud sous drupal 8, on peut utiliser le bon vieux HOOK_form_alter(), mais on peut aussi faire quelque chose de plus « propre » en altérant le type d'entité pour redéfinir son formulaire.

Cela se passe en deux étapes.

Drupal - Surcharger la classe de contrôle d'accès d'un type d'entité

Sous drupal 8, les types d'entités, comme les noeuds, viennent avec leur classe pour gérer le contrôle d'accès (création / modification / visualisation / suppression).

Il est possible de surcharger ces classes pour personnaliser plus finement ce contrôle.

Commentaires

OANDA FX Introduction

OANDA FX, frequently called OANDAFX, is a prominent digital forex dealer that caters to a wide range of traders, including novices and seasoned professionals.

Target Audience and User Base

The platform is designed for clients with varying trading experience, spanning newcomers to professional forex dealers. This inclusive approach provides that all users can find value in its services.

Trading Platforms plus Tools

OANDA FX delivers multiple trading platforms, including its own proprietary platform and the widely used MetaTrader 4 (MT4). These interfaces enable effective forex trading with cutting-edge charting tools, market analysis, and tailorable settings that match the personalized needs of traders.

Educational Resources

Understanding the needs of inexperienced traders, OANDA FX invests in comprehensive learning resources, including webinars, tutorials, and detailed market commentary. This emphasis on training helps ensure that new traders build skills before engaging in live trading.

Regulation plus Security

OANDA FX operates under strong regulatory frameworks in multiple jurisdictions like the US, UK, Canada, and Australia. This compliance ensures security for traders’ funds and honest trading practices, building confidence among its client base OANDA ポジション

Customer Support along with Service

The broker offers robust customer support via live chat, email, and phone, available in multiple languages. This dedicated support staff supports traders with any issues, ranging from technical problems to account management inquiries.

Conclusion

OANDA FX stands out as a flexible forex platform that successfully addresses the demands of traders at every level. With its advanced platforms, extensive educational tools, and strong regulatory frameworks, OANDA FX stands firmly as a trusted name in the forex trading industry.

OANDA FX Summary

OANDA FX, frequently called OANDAFX, is a prominent online forex dealer that serves a diverse spectrum of traders, covering both new and expert users.

Target Audience and User Base

The platform is designed for traders of all levels, spanning newcomers to professional forex practitioners. This comprehensive approach ensures that everyone can get advantages in its services.

Trading Platforms and Tools

OANDA FX provides a variety of trading interfaces, such as its own proprietary platform and the widely used MetaTrader 4 (MT4). These interfaces enable seamless forex trading with cutting-edge charting tools, market analysis, and personalized settings that match the personalized needs of traders.

Educational Materials

Understanding the needs of inexperienced traders, OANDA FX offers comprehensive instructional resources, including webinars, tutorials, and detailed market commentary. This emphasis on training helps make sure that novices develop proficiency before engaging in live trading.

Regulation plus Security

OANDA FX operates under robust regulatory frameworks in multiple jurisdictions like the US, UK, Canada, and Australia. This compliance provides safety for traders’ funds and clear trading practices, fostering reliability among its client base OANDA ポジション

Customer Support and Service

The broker provides comprehensive customer support via online chat, email, and phone, available in multiple languages. This dedicated support staff helps traders with all issues, ranging from technical glitches to account management inquiries.

Conclusion

OANDA FX stands out as a multi-purpose forex service that successfully addresses the needs of both novice and expert traders. With its innovative platforms, comprehensive educational tools, and strong regulatory frameworks, OANDA FX continues to be a respected name in the forex trading industry.

OANDA FX Summary

OANDA FX, frequently called OANDAFX, is a leading online forex dealer that caters to a broad range of traders, from beginners to experienced.

Target Audience including User Base

The platform is designed for investors at different skill levels, starting from novices to highly experienced forex traders. This comprehensive approach provides that everyone can find value in its tools.

Trading Platforms as well as Tools

OANDA FX provides a variety of trading interfaces, including its own proprietary platform and the popular MetaTrader 4 (MT4). These interfaces support seamless forex trading with advanced charting tools, market analysis, and personalized settings that match the unique needs of traders.

Educational Resources

Understanding the needs of inexperienced traders, OANDA FX offers comprehensive learning resources, including webinars, guides, and detailed market commentary. This focus on education helps guarantee that novices build skills before engaging in live trading.

Regulation and Security

OANDA FX operates under strict regulatory frameworks in multiple jurisdictions like the US, UK, Canada, and Australia. This official supervision ensures protection for traders’ funds and honest trading practices, building reliability among its client base OANDA Japan

Customer Support along with Service

The broker delivers robust customer support via live chat, email, and phone, available in multiple languages. This committed support staff helps traders with various issues, ranging from technical glitches to account management inquiries.

Conclusion

OANDA FX stands out as a versatile forex broker that effectively addresses the demands of both novice and expert traders. With its advanced platforms, rich educational tools, and reliable regulatory frameworks, OANDA FX continues to be a dependable name in the forex trading industry.

OANDA FX Introduction

OANDA FX, also known as OANDAFX, is a leading online forex broker that caters to a diverse spectrum of traders, covering both new and expert users.

Target Audience as well as User Base

The platform accommodates traders of all levels, ranging from newcomers to professional forex dealers. This inclusive approach provides that any trader can get advantages in its features.

Trading Platforms plus Tools

OANDA FX offers a variety of trading systems, including its own proprietary platform and the popular MetaTrader 4 (MT4). These interfaces support efficient forex trading with state-of-the-art charting tools, market analysis, and customizable settings that fit the individual needs of traders.

Educational Support

Understanding the needs of novice traders, OANDA FX provides comprehensive instructional resources, including webinars, guides, and detailed market commentary. This focus on education helps ensure that beginners build skills before engaging in live trading.

Regulation together with Security

OANDA FX operates under strict regulatory frameworks in multiple jurisdictions like the US, UK, Canada, and Australia. This regulatory oversight ensures safety for traders’ funds and transparent trading practices, building reliability among its client base OANDA ポジション

Customer Support plus Service

The broker delivers robust customer support via instant messaging, email, and phone, available in multiple languages. This responsive support personnel helps traders with all issues, ranging from technical problems to account management inquiries.

Conclusion

OANDA FX is recognized as a multi-purpose forex broker that competently caters to the needs of a diverse trader audience. With its cutting-edge platforms, rich educational tools, and robust regulatory frameworks, OANDA FX stands firmly as a trusted name in the forex trading industry.

OANDA FX Summary

OANDA FX, also known as OANDAFX, is a leading internet-based forex platform that serves a broad spectrum of traders, from beginners to experienced.

Target Audience as well as User Base

The platform accommodates investors at different skill levels, spanning novices to professional forex practitioners. This inclusive approach guarantees that all users can benefit in its services.

Trading Platforms plus Tools

OANDA FX provides several trading systems, including its own proprietary platform and the widely used MetaTrader 4 (MT4). These platforms facilitate seamless forex trading with state-of-the-art charting tools, market analysis, and tailorable settings that fit the personalized needs of traders.

Educational Materials

Understanding the needs of new traders, OANDA FX invests in comprehensive instructional resources, including seminars, tutorials, and detailed market commentary. This emphasis on training helps guarantee that new traders build skills before engaging in live trading.

Regulation together with Security

OANDA FX operates under strict regulatory frameworks in multiple jurisdictions like the US, UK, Canada, and Australia. This regulatory oversight provides security for traders’ funds and clear trading practices, creating trust among its client base OANDA 為替レート

Customer Support along with Service

The broker offers comprehensive customer support via online chat, email, and phone, available in multiple languages. This committed support personnel supports traders with all issues, ranging from technical problems to account management inquiries.

Conclusion

OANDA FX stands out as a multi-purpose forex broker that competently caters to the requirements of a diverse trader audience. With its advanced platforms, comprehensive educational tools, and strong regulatory frameworks, OANDA FX continues to be a dependable name in the forex trading industry.

OANDA FX Summary

OANDA FX, frequently called OANDAFX, is a leading digital forex broker that serves a wide spectrum of traders, including novices and seasoned professionals.

Target Audience and User Base

The platform targets investors at different skill levels, starting from complete beginners to highly experienced forex dealers. This inclusive approach provides that everyone can benefit in its tools.

Trading Platforms plus Tools

OANDA FX offers a variety of trading interfaces, like its own proprietary platform and the popular MetaTrader 4 (MT4). These platforms enable efficient forex trading with cutting-edge charting tools, market analysis, and personalized settings that fit the individual needs of traders.

Educational Resources

Understanding the needs of inexperienced traders, OANDA FX invests in comprehensive instructional resources, including seminars, tutorials, and detailed market commentary. This emphasis on training helps make sure that beginners gain confidence before engaging in live trading.

Regulation and Security

OANDA FX operates under strong regulatory frameworks in multiple jurisdictions like the US, UK, Canada, and Australia. This official supervision provides security for traders’ funds and transparent trading practices, creating confidence among its client base OANDA ポジション

Customer Support along with Service

The broker offers robust customer support via instant messaging, email, and phone, available in multiple languages. This dedicated support personnel assists traders with various issues, ranging from technical glitches to account management inquiries.

Conclusion

OANDA FX is recognized as a multi-purpose forex service that competently caters to the needs of traders at every level. With its cutting-edge platforms, comprehensive educational tools, and strong regulatory frameworks, OANDA FX continues to be a dependable name in the forex trading industry.

OANDA FX Overview

OANDA FX, frequently called OANDAFX, is a prominent internet-based forex platform that caters to a broad variety of traders, from beginners to experienced.

Target Audience including User Base

The platform is designed for traders of all levels, spanning novices to advanced forex dealers. This comprehensive approach provides that everyone can get advantages in its features.

Trading Platforms and Tools

OANDA FX delivers multiple trading systems, including its own proprietary platform and the popular MetaTrader 4 (MT4). These interfaces support effective forex trading with cutting-edge charting tools, market analysis, and personalized settings that fit the unique needs of traders.

Educational Materials

Understanding the needs of inexperienced traders, OANDA FX invests in comprehensive learning resources, including webinars, step-by-step manuals, and detailed market commentary. This focus on education helps guarantee that new traders build skills before engaging in live trading.

Regulation and Security

OANDA FX operates under robust regulatory frameworks in multiple jurisdictions like the US, UK, Canada, and Australia. This compliance ensures protection for traders’ funds and honest trading practices, creating trust among its client base [url=https://golf-lessons.jp/]OANDA証券[/url]

Customer Support plus Service

The broker provides robust customer support via instant messaging, email, and phone, available in multiple languages. This committed support team helps traders with various issues, ranging from technical glitches to account management inquiries.

Conclusion

OANDA FX stands out as a multi-purpose forex platform that successfully caters to the needs of both novice and expert traders. With its innovative platforms, rich educational tools, and reliable regulatory frameworks, OANDA FX continues to be a dependable name in the forex trading industry.

OANDA FX Overview

OANDA FX, frequently called OANDAFX, is a prominent online forex platform that focuses on a wide spectrum of traders, covering both new and expert users.

Target Audience as well as User Base

The platform accommodates investors at different skill levels, ranging from newcomers to highly experienced forex traders. This inclusive approach guarantees that everyone can find value in its features.

Trading Platforms and Tools

OANDA FX provides multiple trading interfaces, like its own proprietary platform and the widely used MetaTrader 4 (MT4). These environments support seamless forex trading with state-of-the-art charting tools, market analysis, and tailorable settings that match the individual needs of traders.

Educational Materials

Understanding the needs of inexperienced traders, OANDA FX provides comprehensive learning resources, including webinars, guides, and detailed market commentary. This focus on education helps ensure that beginners gain confidence before engaging in live trading.

Regulation together with Security

OANDA FX operates under strong regulatory frameworks in multiple jurisdictions like the US, UK, Canada, and Australia. This compliance guarantees security for traders’ funds and clear trading practices, building reliability among its client base アンダグループ

Customer Support along with Service

The broker offers comprehensive customer support via online chat, email, and phone, available in multiple languages. This responsive support staff helps traders with any issues, ranging from technical difficulties to account management inquiries.

Conclusion

OANDA FX is known as a multi-purpose forex broker that effectively addresses the needs of both novice and expert traders. With its cutting-edge platforms, comprehensive educational tools, and robust regulatory frameworks, OANDA FX continues to be a respected name in the forex trading industry.

OANDA FX Overview

OANDA FX, commonly referred to as OANDAFX, is a well-established online forex dealer that focuses on a broad spectrum of traders, from beginners to experienced.

Target Audience including User Base

The platform targets traders of all levels, starting from novices to advanced forex traders. This versatile approach guarantees that any trader can benefit in its features.

Trading Platforms as well as Tools

OANDA FX offers a variety of trading platforms, such as its own proprietary platform and the widely used MetaTrader 4 (MT4). These platforms facilitate efficient forex trading with advanced charting tools, market analysis, and customizable settings that adapt to the personalized needs of traders.

Educational Materials

Understanding the needs of new traders, OANDA FX invests in comprehensive educational resources, including webinars, step-by-step manuals, and detailed market commentary. This commitment to learning helps ensure that new traders gain confidence before engaging in live trading.

Regulation and Security

OANDA FX operates under strong regulatory frameworks in multiple jurisdictions like the US, UK, Canada, and Australia. This regulatory oversight provides security for traders’ funds and clear trading practices, building confidence among its client base OANDA ポジション

Customer Support along with Service

The broker delivers robust customer support via instant messaging, email, and phone, available in multiple languages. This responsive support personnel assists traders with all issues, ranging from technical difficulties to account management inquiries.

Conclusion

OANDA FX stands out as a flexible forex service that effectively addresses the requirements of both novice and expert traders. With its advanced platforms, comprehensive educational tools, and reliable regulatory frameworks, OANDA FX stands firmly as a respected name in the forex trading industry.

Ajouter un commentaire

Ne sera pas publié
CAPTCHA
Désolé, pour ça, mais c'est le seul moyen pour éviter le spam...