Adding a callback when reading from an object in Twig

257 views Asked by At

Let's say I have a basic entity called Entity which is mapped to a database table. This entity has got two properties: propertyA and propertyB.

One particularity of this entity is, although we may store whatever we want in these properties, when using the value of propertyB on a Twig template with entity.propertyB we want to systematically truncate the value to 100 characters.

Now, this is perfectly doable in several ways:

  • Truncate the value directly in the getPropertyB() method;
  • Register a Twig extension and create a dedicated filter;
  • Add a lifecycle callback on the entity to truncate the value before the object is actually created.

As this is strictly a display rule, and not a business rule on our entity, the second solution seems to be the best IMHO. However, it demands we apply the filter every time we need to use the value of propertyB in a template. Should an unaware developer come by, the value may not be truncated.

So my question is: is there a way to register some kind of callback, strictly restricted to the view model wrapping our entity, which would allow us to apply some filters on the fly on some of its properties ?

1

There are 1 answers

1
Konstantin Pereiaslov On

Since you never need to access anything beyond 100 characters, you can truncate the property in its setter. This doesn't really pollute Entity code, because this is some logic inherent to it.