Entity Engine in PHP

25 Apr 2011 by Martin Vium

EntityEngine is a nice pattern for externalizing the different components (logic) of an entity (object). And particularly effective in games, where features of an object is shared among many different types. This way the behavior of the object is put into separate components. The idea is that an entity is pretty much just an ID, and the components are referenced via. the entity ID.

<?php
$engine = new EntityEngine();
$entity = new SimpleEntity($engine);
$entity->setComponent(new DialogComponent());
$entity->getComponent('Dialog')->talk();
?>

Alternative:

<?php
$engine->getComponent($entity, 'Dialog')->talk();
?>

Why

Entity engines works very well as an alternative (and improvement) to deep inheritance trees. Inheritance can fall short when, for example you want a Rock to be able to speak (which would require Rock to inherit from Human). Another advantage is that the engine, keep the components in an array based on their type. This means that we can fetch all components of a given type, without knowing (or caring) which entities own them.

<?php
$engine = new EntityEngine();
$entity = new SimpleEntity($engine);
$entity->setComponent(new CollisionComponent());
foreach($engine->getAll('Collision') as $comp) {
     $comp->update();
}
?>

You can find the EntityEngine Interfaces and Implementation on Github.