6

When dealing with nodes on Drupal 8, we usually receive an instance from \Drupal\node\Entity\Node, that is great in many aspects, but i'm not sure on how to extend it so that I can use classes that represent something in my own domain, rather that generically using Node. I can make this here:

class Video extends \Drupal\node\Entity\Node {}

Ok. But to have Video::load() and that sort of things, i'm seeing that I need to probably also extend NodeStorage, because everything returns a Node class and type changing seems to be not so easy in PHP from what i'm seeing until now. I'm not sure if this is really the way to go.

I really like to work extending Node(I used to extend EntityDrupalWrapper on D7), as it becomes easier for newcomers to the project and to have stuff like $Video->getFileUrl()

Any ideas?

2

2 Answers 2

2

The recommended solution is to extend ContentEntityBase which is tedious task if you want to do it manually, or a quick one if you use drupal console and it's generate:entity:content command.

However

It is still possible to extend Node class and so far my experiments prove that it works fine. The important part is that after extending Drupal\node\Entity\Node you also have to tell drupal to use your class instead by implementing hook_entity_type_build.

You can see my detailed answer for How to alter the entity type class in Drupal 8? question that explains how to do this and why it works.

1

You can't do that. All entities of the same type have use the same class.

I believe there are some issues to allow this, possibly through a per-bundle classmap instead of a single class entry, but it would be quite complicated at the moment, as there are different places where entity classes are instantiated and you'd have to override them all (create and load, for example).

2
  • Are you saying that this is a current limitation on Drupal 8 or you disagree that conceptually does make sense to do that? I'm trying to figure out an improved way to work with classes on D8, because on Drupal 7 I simply extended EntityDrupalWrapper, like I said above, but I had to manually instantiate it like $node = node_load($nid); $Video = new Video($node); I'm trying to improve this, now that we have many OO concepts inside D8. However, i'm already thinking that maybe i'm really wrong in trying this way, as Node class is an Entity Type class, not making sense to use as bundle.
    – pedrorocha
    Commented Sep 13, 2015 at 13:16
  • @Berdir, it is possible to do. See drupal.stackexchange.com/a/199395/5982 Commented May 18, 2016 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.