0

To make certain actions simpler I'd like to know if it's possible to extend the node class in a way that allows you to add functions to the node class. What I mean is, I want to be able to perform actions like

$node->test();

or

$node->styledImage('field_name','style');

I was attempting to create it in a custom module like so

<?php

use Drupal\node\Entity\Node as BaseNode;

class AbleNode extends BaseNode {
    public function test(){
        return 'test';
    }
}

but then it dawned on me that this probably would only create a new type of entity that could give me those functions. It wouldn't actually let me perform these actions are preexisting nodes. Is adding functions to the node class possible, or even practical?

5
  • Probably not advised, no. Possible, sure.
    – Kevin
    Oct 11, 2017 at 15:23
  • 1
    see drupal.stackexchange.com/questions/173811/…
    – 4uk4
    Oct 11, 2017 at 15:43
  • @4k4 I saw that but I didn't see how that would allow me to add methods to preexisting nodes.
    – Amy
    Oct 11, 2017 at 15:50
  • I believe the key is hook_entity_type_build. api.drupal.org/api/drupal/…
    – Kevin
    Oct 11, 2017 at 15:56
  • 1
    @Matt When you override the entity class the methods on the new class will be available on all node objects. The code in the highest voted answer in the duplicate is basically a copy/paste of what you need to do in your own module
    – Clive
    Oct 11, 2017 at 15:58

0

Browse other questions tagged or ask your own question.