Zend Model validation
I'm working on Zend application, but have no much experience with Zend, so just relying on my RubyOnRails experience.
From couple articles I've found that most of validation is implemented on Forms level - with Zend_Form. But it looks a bit weird for me - how about to have a validation on model level - create a model based on form data and run smth like $model->isValid();
it makes sens开发者_StackOverflow社区e as I'm creating some models without forms post requests.
My current model flow:
ProductMapper extends Zend_Db_Table
Product extends Zend_Db_Table_Row
And given I'm doing something like
$mapper = new ProductMapper();
$product => $mapper->find(...);
// Do some staff with this model
// And want to check if it's valid before saving
if ($product.isValid()) {
$product.save(); // Zend_Db_Table_Row method
} else {
...
}
I realize that I can simply do validation with RegExp inside isValid
method, but I'd like to use already implemented methods from Zend_Form
like addValidator
, addFilter
and all that usefull things.
Also is this correct way to manage models in Zend?
Any help or suggestions will be very appreciated!
You can use same filters and/or validators as Zend_Form but like this
$validator = new Zend_Validate_Allnum();
if ($validator->isValid($data)
do some code
or
$filter = new Zend_Filter_StringTrim();
$filteredVal = $filter->filter($val);
so you can create your own method isValid() in your row class where you can perform your own logic of validating and filtering values
Models in Zend are not only representations of Db objects, most objects in fact have nothing to do with the database and are Models for business logic. In this context having a global validation method does not make sense. Zend_Db_Table and Row will do some checks for you when playing with db object, like checking which is the primary Key, but if you want something like Active Record you'll have to extend those classes by yourself.
I do not agree that db-layer (ZF objects Table, Row) is right place for validation. IHMO validation is application logic or bussiness constraint.
Validation process must be placed in concrete Model. DB layer has to be clean and is only responsible to do simply database operation (insert, update, delete, select).
Your Model has to know which attributes are required (or datatype of attribute) so there is a right place for validation.
As Elzo said - some Models are not represent DB objects - so you should make interface IPersistenceable which has one method validate for database-driven models. These models must implement own validation algorithm.
This approach is usefull - each model can have various way of validation. Next approach - you can make abstract class with basic validation of primary key + validate method and each persistanceable model extends this class.
精彩评论