Skip to content

Instantly share code, notes, and snippets.

@martinvium
Last active October 9, 2015 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinvium/3486895 to your computer and use it in GitHub Desktop.
Save martinvium/3486895 to your computer and use it in GitHub Desktop.
<?php
class EntityEngine
{
private $components = array();
/**
* @param Entity $entity
* @param string $componentName
* @return Component
*/
public function getComponent(Entity $entity, $componentName)
{
if($this->hasComponent($entity, $componentName)) {
return $this->components[$componentName][$entity->getId()];
}
return null;
}
/**
* @param Entity $entity
* @param string $componentName
* @return boolean
*/
public function hasComponent(Entity $entity, $componentName)
{
return isset($this->components[$componentName][$entity->getId()]);
}
/**
* @param Entity $entity
* @param Component $component
*/
public function setComponent(Entity $entity, Component $component)
{
$this->components[$component->getName()][$entity->getId()] = $component;
}
/**
* @param string $componentName
* @return array of Component
*/
public function getAll($componentName)
{
if(! isset($this->components[$componentName])) {
return array();
}
return $this->components[$componentName];
}
}
interface Entity
{
/**
* @return unique identifier for this instance
*/
public function getId();
/**
* @param string $component
* @return Component
*/
public function getComponent($componentName);
/**
* @param Component $component
*/
public function setComponent(Component $component);
}
abstract class SimpleEntity implements Entity
{
private $engine;
/**
* @param EntityEngine $engine
*/
public function __construct(EntityEngine $engine)
{
$this->engine = $engine;
}
public function getId()
{
return spl_object_hash($this);
}
public function getComponent($componentName)
{
return $this->engine->getComponent($this, $componentName);
}
public function setComponent(Component $component)
{
$this->engine->setComponent($this, $component);
}
}
interface Component
{
public function getName();
}
// Component Implementations of the Examples
class DialogComponent implements Component
{
public function getName()
{
return "Dialog";
}
public function moveRight();
}
class CollisionComponent implements Component
{
public function getName()
{
return "Collision";
}
public function update();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment