csdynamicmodel Port of Yii2 DynamicModel for inline data validation

Yii2 has new feature called DynamicModel which allows you to validate any data in your code using well known model validators. This is a port of that feature for Yii 1.1.

CSDynamicModel is a model class primarily used to support ad-hoc data validation.

The typical usage of CSDynamicModel is as follows,

public function actionSearch( $name, $email ) {
    $model = CSDynamicModel::validateData( compact( 'name', 'email' ), array(
        array( 'name, email', 'length', 'max' => 128 ),
        array( 'email', 'email' ),
    ) );
    if( $model->hasErrors() ) {
        // validation fails
    } else {
        // validation succeeds
    }
}

The above example shows how to validate $name and $email with the help of CSDynamicModel. The validateData() method creates an instance of CSDynamicModel, defines the attributes using the given data (name and email in this example), and then calls Model::validate().

You can check the validation result by hasErrors(), like you do with a normal model. You may also access the dynamic attributes defined through the model instance, e.g., $model->name and $model->email.

Alternatively, you may use the following more "classic" syntax to perform ad-hoc data validation:

$model = new CSDynamicModel( compact( 'name', 'email' ) );
$model->addRule( array( 'name, email', 'string', 'max' => 128 ) )
    ->addRule( array( 'email', 'email' ) )
    ->validate();
if( $model->hasErrors() ) {
    // validation fails
} else {
    // validation succeeds
}

CSDynamicModel implements the above ad-hoc data validation feature by supporting the so-called "dynamic attributes". It basically allows an attribute to be defined dynamically through its constructor or defineAttribute().

Usage

extract to your project structure and use it :) unit test included

5 0
3 followers
226 downloads
Yii Version: Unknown
License: Apache-2.0
Category: Validation
Developed by: Maciej Liżewski
Created on: Feb 1, 2014
Last updated: 10 years ago

Downloads

show all