I’m working on a project where we’re updating our web app with a new Single-Page frontend. We’ve hit a snag with object types from our API.
Our PHP backend adds a ‘_type’ field to JSON exports, helping us handle subclasses. But we also need to know about parent classes sometimes. Here’s what I mean:
AnimalKingdom
WarmBlooded
Person
Canine
...
ColdBlooded
Gator
Serpent
...
When we GET /creatures/, we get:
[
{"_type": "Person", "id": 1, "diet": "Vegetables"},
{"_type": "Canine", "id": 2, "diet": "Meat"},
{"_type": "Gator", "id": 3, "diet": "Fish"}
]
We can’t tell which are WarmBlooded or ColdBlooded anymore. We thought about adding an inheritance chain:
{
"_type": "Person",
"id": 1,
"diet": "Vegetables",
"_ancestry": "AnimalKingdom.WarmBlooded.Person"
}
It’s simple but feels clunky. Is this okay? How would you handle this? Any better ideas?
hey, wat about using a nested structure? like this:
{
"_type": "Person",
"_parent": {
"_type": "WarmBlooded",
"_parent": {
"_type": "AnimalKingdom"
}
},
"id": 1,
"diet": "Vegetables"
}
it keeps the hierarchy clear n u can easily traverse up the chain. might be a bit more verbose tho
Having worked on similar systems, I’d suggest considering a ‘type’ array instead of a single field or string. It could look like this:
{
"types": ["AnimalKingdom", "WarmBlooded", "Person"],
"id": 1,
"diet": "Vegetables"
}
This approach maintains the full hierarchy while keeping it simple and flexible. It’s easy to query and filter on any level of the hierarchy. You can also easily add or remove levels without breaking existing code.
One potential drawback is slightly increased payload size, but the benefits in terms of clarity and ease of use often outweigh this. It’s also more aligned with how many modern frontend frameworks handle component inheritance and type checking.
Remember to document this structure well in your API specifications to ensure all consumers understand how to interpret and use the type information correctly.
I’ve faced a similar challenge in my work, and I can share what worked for us. Instead of using a flat ‘_ancestry’ string, we opted for a more structured approach using a ‘_hierarchy’ object. It looked something like this:
{
"_type": "Person",
"id": 1,
"diet": "Vegetables",
"_hierarchy": {
"base": "AnimalKingdom",
"intermediate": ["WarmBlooded"],
"specific": "Person"
}
}
This structure gave us more flexibility. We could easily query for all WarmBlooded creatures or all AnimalKingdom entities without parsing strings. It also made it simpler to add or remove intermediate levels without breaking existing code.
One caveat: this approach does increase the payload size slightly. But in our case, the improved clarity and ease of use on the frontend outweighed the minor increase in data transfer. It’s a trade-off you’ll need to evaluate based on your specific requirements and constraints.