symfony

You are currently browsing the archive for the symfony category.

I recently wrote a model-validation plugin for symfony. I believe this plugin, or something like it, should be included in the symfony core. Here’s why.

In an MVC architecture, the model layer (the M in “MVC”) encapsulates the data model of our application. This includes not only data storage and access, but also validation – that is, the data model should specify what data is allowed, and what is forbidden. In symfony, for example, the save() method of every data object should first validate the object. Thus, in a strict MVC architecture, we should perform only form-specific validation in the controller. But in a web application, since almost all data that needs to be validated comes from web forms, we often “cheat” by validating the form data in the controller layer instead of validating within the model. symfony does things this way. While there are several efficient ways of validating forms in symfony, they all occur between the end-user’s submission of a form, and the corresponding “update” action. Thus, symfony provides support only for controller-based validation. To be fair, we can validate within the model, by overriding the validate() method of each data class in our model. But this represents a lot of repeated code. Furthermore, if we want to use YAML files to specify validation, or if we want to set errors that can be accessed from the presentation layer, we must manually call functions to accomplish these things.

It would be better if we could use symfony’s automated validation logic from within the model. This would not only allow, but encourage developers to move validation related to the data model out of the controller and into the model. Doing so not only helps us understand our application conceptually; it also protects our data from bugs in the presentation layer. As developers, we are wise to be skeptical of ourselves, especially when the security of our data may depend on it. Encapsulation can also protect us from bugs in the framework itself, like this one.

For the application I am currently developing, data security is the top priority. So I wrote the sfPropelValidateBehavior plugin. Now you can associate your validation logic with your data classes and put it in your project’s “model” directory. In most cases, you can copy the configuration from you form-validation files as-is. I hope this helps you other symfony developers!

Newer entries »