Single Table Inheritance - Good or bad idea?
Hey there.
I am currently building a browser game where the player has to manage a village. A village consist of multiple buildings. Buildings have levels and, based on a level of a building, some stats about the village change.
For example, if the farm gets levelled up, the maximum population increases. Or if the wall gets improved, the village gets more defence points.
Now, straight to my problem.
When the player unlocks a new Level of a building, a BuildingUpdated event is fired. Now I need to figure out, which steps I need to take, to handle the "level up" of a building. In other words, I need to somehow figure out, which method to call to handle this event. And it should be somewhat polymorphic, because only a switch case is not an option, for obvious reasons.
My current idea is, to use single table inheritance for this. So I would have a table Buildings, which defines the basic stats about a building (name, max_level, etc). Also, i would add a field type, in which i would save the class name of the class, which would handle the event. When fetching a record from this table, Eloquent would automatically resolve this type field and instantiate the appropriate object for me.
So, expressed in code:
My Building Eloquent Model:
class Building extends Model
{
use SingleTableInheritanceTrait;
protected $table = 'buildings';
protected static $singleTableTypeField = 'type';
protected static $singleTableSubclasses = [Headquarter::class, Farm::class, Warehouse::class];
// ...
}
A specific building, inheriting from the Eloquent model:
class Farm extends Building
{
protected static $singleTableType = Farm::class;
public function whenUpgraded($village, $level)
{
// Do work to upgrade the village appropriate
}
}
And my DB table:
Schema::create('buildings', function (Blueprint $table) {
$table->increments('id');
$table->string('type');
$table->timestamps();
});
For reference, i would use this package: Nanigans/single-table-inheritance
So, what do you guys think of this? Is single table inheritance straight up bad in your eyes? If so, why is it?
Do you have other ideas for solving this problem?
Let´s hear what you think.
Please or to participate in this conversation.