With ECK I created Entity type Vehicle, and added 2 bundles, Car and Truck

Goal is to have a class Car so I can use Car::create() and similar entity functions, and also implement my own functions.

As far as I came is creating Vehicle class, and it's working, but I'm struggling with bundles.

1 Answer 1


I guess it is impossible to do what you want. A bundle is not a sub-class of an entity as you seem to be assuming.

Classes are always defined in code and are always provided by a module. ECK uses a workaround but in fact only defines one entity type: EckEntity, it then performs some tricks to let Drupal see this as different entity types.

Creating entities for every bundle dynamically (since a user can add / remove bundles) would be difficult and appears to be only possible using dirty tricks like this:

// With a property
$myclassname = "anewclassname";
$myproperty = "newproperty";
eval("class {$myclassname} { protected \${$myproperty}; }";

From: https://stackoverflow.com/a/15579465/1293725

I am pretty sure Drupal does not support this (luckily).

Bundles are stored as properties on the entity, often (always?) as the type property, have a look at this example:

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article', // < - this is the bundle
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
    'alt' => 'Hello world',
    'title' => 'Goodbye world'

From: https://drupal.stackexchange.com/a/189095/9921

So in your case, you would need to do this:

$car = Vehicle::create([
  'type'        => 'car',

Or define a new class for your bundles, but you would need to either use the eval method above to create a class for all your bundles, or define them in code and loose flexibility. Then in that class extend the Vehicle class and in the constructor provide the type or something. For the sake of readability of your code I guess it would be best to just follow conventions and not create classes for bundles.


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