The original url:http://blog.csdn.net/u012859646/article/details/16840299 [2012.3] just have a small function to achieve, it may be a period of time without writing code, a bit of cleanliness, want to put the code As much as possible to write a clean point, below is a need to optimize the case (just in PHP, as explained by PHP).
If there is a function foo ($uid, $phone, $email, $sex, $age), for the legitimacy of the data, we first have to do parameter validation, this is very important, in high-quality programming habits believe there will be a "never trust external data." Well, generally how to write, consider the following two possible scenarios:
Programme I
if (! ( Valid_uid ($uid) && valid_phone ($phone) && valid_email ($email) && valid_sex ($sex) && Valid_age ($age)) ) {
LOG ("Invalid arg!");
}
The benefit of this scheme is that it is written with only one line and the code volume is saved. However, it is not possible to accurately print out the error parameters. You may be able to output all parameters to the log, but such a log to see clearly the problem must also be a lot of energy.
Programme II
if (!valid_uid ($uid)) {
LOG ("Invalid UID");
}
if (!valid_phone ($phone)) {
LOG ("Invalid Phone");
}
if (!valid_email ($email)) {
LOG ("Invalid email")
}
This scheme looks like the log is refreshing, you can locate which parameter is illegal. The problem is also obvious, these 5 parameters will have to compensate for n lines of code. In addition to increasing the amount of code, this scenario is not an elegant solution.
Want to implement such a check method, first can maintain the minimum amount of code, but also can accurately identify the problematic parameters. Inspired by cascading calls, you can use the following scenario three to implement a generic check class validator.
Programme III
$VD = new Validator ();
$VD->uid ($uid)->phone ($phone)->email ($email)->sex ($sex)->age ($age);
if ($vd->fail ()) {
LOG ($VD->err_msg ());
}
The idea has, the realization is actually very simple, here does not stick the code. This scheme is not specific to PHP language features and is easily ported to other languages.
2012.3
--end--