Glad to see that someone else sees the value in this idea. Frankly, I gave up on it because everyone seemed to ignore it on this forum. Perhaps I should give a usage example. Let’s suppose we have an active record class named User:
class User extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @return User the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'user';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name', 'length', 'max'=>255),
//example of a costly validation rule
array('country_id', 'exist', 'className' => 'Country', 'attributeName' => 'id'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name', 'safe', 'on'=>'search'),
);
}
/**
* @return array sanitization rules for model attributes.
*/
public function sanitizationRules()
{
return array(
//supposing there is a built-in sanitization class for trimming a string
array('name', 'trim', 'length' => 20),
//suposing there is a built-in sanitization class that filters a string using regex
array('name', 'filter', 'pattern', '/\W/'), //filter out non-word characters
);
}
}
As you can see, I’ve added a method sanitizationRules() that looks very similar to rules(). In this example, I have 2 rules: the first one trims username to 20 chars and the second one filters out any non-word characters. Now, all this can be accomplished by adding these sanitization rules to the existing validation rules. The only difference is that sanitization would be performed on assignment, so as soon as you do:
$user->name = "Jim O'Rourke";
sanitization would be immediatelly performed and name would be transformed to “Jim ORourke” (let’s pretend that this is what we want to achieve). Also, you will not be forced to perform validation (which might be costly) if all you need to do is sanitize data. In addition, you will have a clean separation of validation logic from sanitization logic, instead of mixing them all together.
Hope this makes more sense now.