Validate Action Parameters Using A Form Model

A frequent topic in REST/API design discussions is how to relay bad request messages back to the user, e.g. "ID is required" or "Type must be x,y,z."

It may sound silly, but I haven’t seen mentioned that a FormModel can be used to validate those inputs. If implemented as a controller property, you can very easily construct filters for bad requests that relay complex, intelligent error messages back to the end user. Here’s the gist of it (Github code):

  • Add a $_params property to your Controller.

  • Create an ActionParamsForm model for your controller

  • Use action IDs as scenario names.

  • Override getActionParams() to load the appropriate form model into Controller::$_params

  • Populate the form’s attributes from whatever source you want, e.g. $_GET/$_POST.

  • Add a filter that validates the form model and throws a 400 on failure

Hope this helps!