Preciel
Preciel

Reputation: 2837

Generic type function parameter

I'm currently making a new Twig extension.
This Twig extension accept as parameter en entity object (\AppBundle\Entity\*) and a parameter name.

public function filterNameFilter($entity, $parameter) {}

What I would like to do is have a type on $entity which would be one of the class in Appbundle\Entity (can be any) and have Symfony guess which one it's.

Is it possible?

Upvotes: 0

Views: 76

Answers (1)

Jovan Perovic
Jovan Perovic

Reputation: 20201

I believe this is not something related to Symfony, but rather to PHP's weak typed nature.

One way to handle is to have your function be capable of checking its type via instanceof, but that is considered an anti-pattern due to to the fact that you need to readjust this function every time you decide to add a new class which requires this type of handling.

Another way to potentially handle this is to identify common interface and have all of your classes within that namespace implement it. That way, in your Twig extension you can specify interface type-hint. Feasibility of this really depends on what you want to achieve.

Hope this sheds some light...

Upvotes: 1

Related Questions