I'm currently implementing functionality in Symfony (PHP - not that it should make any difference which language I'm using) where I have about four controllers that do almost exactly the same thing. The only difference between them is that they use different entity objects and form objects.
I've already refactored all the common functionality into an abstract parent class. I then have two abstract methods called getEntityInstance
and getFormInstance
, which only return the appropriate object instances.
The entity and form instances returned would both have common interfaces, called AbstractQuery
and AbstractForm
respectively.
As an example, let's say I have the following two classes.
abstract class AbstractQueryController {
abstract protected function getEntityInstance();
abstract protected function getFormInstance(AbstractQuery $query);
public function queryAction(Request $request) {
//Do some stuff
$form = $this->getFormInstance($this->getEntityInstance());
//Do something with $form
}
}
class SomeRandomController extends AbstractQueryController() {
protected function getEntityInstance() {
return new SomeRandomQuery();
}
protected function getFormInstance(AbstractQuery $query) {
return new SomeRandomForm($query);
}
}
Now this approach works, but it looks wrong. What design pattern or other concept should be applied here to make the code "cleaner"? The issue is that, with every new controller that extends AbstractQueryController
, I'm basically baking the "configuration" (if you can call it that) into the child class, which looks incorrect.