How to handle initializing and populating forms in Expressive?


I keep coming across the same issue, where my action (aka end-point middleware) needs to use a form, and the form must be populated with values before it is used. By populating I mean both filling out the select elements with any default options, and also setting any default values and setting any choices as selected.

So far what I am doing is this - in my action factory I instantiate the form and also initialize the “population service” for the form. I inject both of those classes into my middleware action’s constructor. The inside the action I then use the form service to populate the form.

It feels correct in a sense that I am using DI and SRP but also it feels unnecessarily bloated -> if I have two forms, do I inject 4 classes into the action? (2 form population services and two forms)?

I am part debating that to reduce the bloat, I may wish to instantiate forms inside the action instead of at service creation time. And if I perhaps want to only have one service to populate all forms, no matter what those forms are.

But before I go inventing my own way of doing this, is there an established pattern to handle this issue?
P.S. I am using Zend\Form in my case.

  • use factories for the forms, which uses your “form population services”, then forms are ready
  • add the FormElementManager to your action classes and pull the forms from the manager

Here can you find some infos to the FormElementManager:

(If you use a factory for a form, maybe you can discard the related “population service”.)