-- Ralf Eggert <[EMAIL PROTECTED]> wrote (on Friday, 28 November 2008, 04:43 PM +0100): > I am currently thinking about the best practice for handling forms, > models, validators and filters with the Zend Framework. > > Think of a user model with username, emailaddress and a password fields. > The model uses a Zend_Db_Table object for data storage. The username > field should only contain alphanumeric values with a length between 4 > and 32 signs, the emailaddress field should only contain valid email > addresses and the password must have a minimum length of 10 signs and > should contain at least one char and one number. All fields should be > filtered with a trim and as striptags filter. > > This model needs forms for registration, login and update. The > registration form contains all three fields as required fields, the > login form only contains username and password both as required fields > and the update form contains all fields, but the password field is not > required. > > Where and how would you define the validator and filter rules? > > a) Within the model. If yes, how can the form access these rules? > b) Within the form. If yes, how can the model access these rules > and does the model really need to access these rules? > c) In both the model and form. Not a good idea to duplicate the > definitions, I think. > d) Outside of the model and form in definition files (INI, XML). Both > the model and the form can read these files via Zend_Config > whenever they need them. > e) Create an object that contains the rule definitions. Both the model > and form can access this object to get the validation and filter > rules when needed. > f) maybe your idea...
What I've started doing and recommending is to attach forms to your model, and to use forms for model validation. As an example, an "add()" method in your model might have the following: public function add(array $data) { $form = $this->getForm(); if (!$form->isValid($data)) { return false; } if (!$id = $this->getTable()->insert($form->getValues())) { throw new Exception('Unable to insert record'); } return $id; } This is particularly feasible since 1.6.0, when all plugins were modified to allow lazy-loading -- if you don't render a form, the actual decorator objects will not be instantiated, and if you're rendering a form for the first time, validators will not be loaded. Another benefit is that your models now also have a concrete representation as a form. Basically, the technique prevents code duplication, and relates forms and models semantically. (For a practical example, you can look at the pastebin demo app at http://github.com/weierophinney/pastebin -- look under application/models/). -- Matthew Weier O'Phinney Software Architect | [EMAIL PROTECTED] Zend Framework | http://framework.zend.com/