1

I am trying to figure out the best place to put the code where I access the database and populate the values for the options in a select element. It seems clumsy to put this code in the controller. What are the drawbacks of having forms be aware of the database?

blacktie24
  • 4,985
  • 6
  • 41
  • 52

1 Answers1

1

The drawback of having forms aware of the database is that you will get tightly coupled components - Zend_Form and your database access layer in the case above - while these 2 must not have anything in common.

Imagine possible scenarios:

  • You move your data from one database to another. Or you want to add a caching layer on the top of it. You will have to modify db specific calls throughout your project.
  • You decide to unit test your class. You will need to maintain the db connection in tests (or a mock for it).
  • You want to use the same form class in another place and have select stuffed with options not from the database but from ini config file... well, you got the idea.

So the best solution would be having some db-specific mapper class which can get you data you want. And then pass this data as a dependency to the form. That way you will have your form independent (read maintainable, testable) from any outer layers.

So you may create an object of your form, pass it the data from your data source (whatever it is) in the controller.

Max Ivanov
  • 5,695
  • 38
  • 52
  • thx for the reply. If i have to populate several select options, and after validation also convert the selected values into objects, won't this lead to a very fat controller? Is there a way to move this type of form pre/post processing into some type of helper object? – blacktie24 Jul 13 '13 at 23:54
  • 1
    Sure. Next step would be moving your creation code to some dedicated classes - factories (see [What is a Factory Design Pattern in PHP?](http://stackoverflow.com/questions/2083424/what-is-a-factory-design-pattern-in-php) for a nice example). I suppose you need a factory to produce a form and a factory to produce some resulting object from a validated form, so it can be persisted. – Max Ivanov Jul 14 '13 at 00:31