I have some heavy-lifting occurring in my entity’s accessors but only need these for drawing a complex SVG chart that I’m building. I’m loading the data into the DOM via AJAX so these virtual fields are in my $_virtual class member. However, sometimes I just need the basic db fields and not any of the calculated values from my accessors.
How can I “turn off” these values on a per-query basis?
I’ve tried just selecting the ones I need (via fields key in a contain), but the virtual ones still come back to me.
I assume you are sending serialized (JSON) response. To prevent the virtual fields from being included in serialized data set them as hidden using Entity::setHidden().
Ok debugging with toArray() shows that the property isn’t there, but my db queries in that accessor are still executing. So I’m wondering if there’s a way to simply turn this off on a case by case basis? It’s looking like there isn’t, however.
You could maintain two entity classes and use the Table::setEntityClass just before the query.
Personally I like this kind of OOPy solution. I think I’d actually inherit, like this:
class Simple extends Entity {
// all the basic stuff
}
class SvgVersion extends Simple {
// all the heavy lifting and virtual fields
}
This means in you code you get three levels of type-hinting that can make your code easier to understand compared to a system where a single Entity class acts differently at different times
//type hint examples
$this->svgProcess(SvgVersion $entity); //when only the best will do
$this->doSomething(Simple $entity); //when either entity type will work
$this->table->patchEntity(EntityInterface $entity, $data), when anything will work
Is there ever actually a need to have this virtual field included in any auto-generated output (JSON or array conversion)? If not, just don’t list it in the $_virtual array…